자바에서 10진수를 16진수로 변환시

출처 : http://ismydream.tistory.com/144

프로그래밍/JAVA 2013/09/10 02:23

자바에서 10진수를 16진수로 변환시


자바에서 10진수를 16진수로 변환해서 출력하게 되면 아래와 같은 결과가 표시됩니다.

우선 자바에서 사용된 소스코드는 아래와 같습니다.

숫자를 int 형 변수에 담을 때와 double 형 변수에 담을 때의 출력값이 다르게 표시됩니다.

int 형 변수에는 익히 봐왔던 결과가 출력됩니다.

for( int i=1; i<20; i++){

System.out.print( i + ": \t");

System.out.println( Integer.toHexString(i));

}

========================================================

1:  1

2:  2

3:  3

4:  4

5:  5

6:  6

7:  7

8:  8

9:  9

10:  a

11:  b

12:  c

13:  d

14:  e

15:  f

16:  10

17:  11

18:  12

19:  13


따라서 double 일때의 결과값에 대해 살펴보겠습니다.

for(double d1 = 1.0 ; d1< 10.0 ; d1++) {  

  System.out.println(d1+" :  "+Double.toHexString(d1));  


========================================================

1.0 : 0x1.0p0

2.0 : 0x1.0p1

3.0 : 0x1.8p1

4.0 : 0x1.0p2

5.0 : 0x1.4p2

6.0 : 0x1.8p2

7.0 : 0x1.cp2

8.0 : 0x1.0p3

9.0 : 0x1.2p3


출력된 결과를 유심히 보면서 

과연 출력된 값의 의미가 뭘까 궁금했습니다.

우선 

0x1.0p0 를 보면 맨 앞의 두글자 0x 는 16진수를 나타내는 문자이며 1.0p0 는 10진수 1이 16진수로 변경된 숫자 입니다.

어떻게 10진수 1이 1.0p0 로 변경된걸까

우선 16진수를 10진수로 변경하는 공식은 1.0p0 가 a.bpc 라고 할때

(( a * 16 ^ 0 ) + ( b * 16 ^ -1 )) *  2 ^ c 입니다.

따라서 ((1 * 16 ^0) + ( 0 * 16 ^ -1)) * 2^0 이게 됩니다.


조금 복잡하게는 10진수 7인 0x1.cp2 는

(( 1 * 16 ^0 ) + ( 12 * 16 ^ -1 )) * 2 ^ 2 이게 됩니다.

( 1 + 12 / 16 ) * 4 = ( 4 / 4 + 3 / 4 ) * 4

= 7 이게 됩니다.


import java.util.Scanner;


class Basic23{

      static int dec;

      static int[] num= new int[5];

      public static void main(String[] args){

            Menu m=new Menu();

            m.start();

            Calc f=new Calc();

            switch(m.choice){

            case 1 : 

                  for(int i=0;i<5;i++){

                  num[i]=f.bi();

                  } break;

            case 2 :

                  for(int i=0;i<5;i++){

                  num[i]=f.octal();

                  } break;

            case 3 :

                  for(int i=0;i<5;i++){

                  num[i]=(char)f.hex();

                  } break;

            default : System.out.println("error!");

            }

            for(int i=0;i<5;i++){

                  System.out.print(Integer.toHexString(num[4-i]));

            }

            return;

       }

}


class Menu extends Basic23

{

      int choice=0;

      

      public void start(){

            Scanner userInputScanner = new Scanner(System.in);

            System.out.println("Dec to Another");

            System.out.println("Input a decimal number:");

            dec= userInputScanner.nextInt();

            System.out.println("Menu");

            System.out.println("1.Dec to Bi");

            System.out.println("2.Dec to Octal");

            System.out.println("3.Dec to Hex");

            choice= userInputScanner.nextInt();

      }

}


class Calc extends Basic23{

      public int bi(){

            dec = dec/2;

            return dec==1 ? 1 : (dec%2);

      }

      public int octal(){

            int temp=dec;

            if(temp>=8) {dec=dec/8; return temp%8;}

            else {dec=dec/8; return temp;}

      }

      public int hex(){

            int temp=dec;

            if(temp>=16){ dec=dec/16;

                  return temp%16;

                  }

                  

            else {dec=dec/16;

                  return temp;

                  }

                  

      }

}



  1. 1514756 1.jpg
    1
    Import the Scanner class. You can either choose to import thejava.util.Scanner class or the entire java.util package. To import a class or a package, add one of the following lines to the very beginning of your code: 
    import java.util.Scanner; // This will import just the Scanner class.
    import java.util.*; // This will import the entire java.util package.
    
    Ad
  2. 1514756 2.jpg
    2
    Initialize a new Scanner object by passing the System.in input stream to the constructor. System.in is the standard input stream that is already open and ready to supply input data. Typically this stream corresponds to keyboard input. 
    Scanner userInputScanner = new Scanner(System.in);
    
  3. 1514756 3.jpg
    3
    You can now read in different kinds of input data that the user enters. The Scanner class supports getting primitives such as int, byte, short, long in addition to getting strings. Here are some methods that are available through the Scanner class:
    • Read a byte - nextByte()
    • Read a short - nextShort()
    • Read an int - nextInt()
    • Read a long - nextLong()
    • Read a float - nextFloat()
    • Read a double - nextDouble()
    • Read a boolean - nextBoolean()
    • Read a complete line - nextLine()
    • Read a word - next()
    Here is an example of a program that uses different methods of the Scanner class to get different types of input: 
    import java.util.Scanner;
     
    public class ScannerExample {
        public static void main(String[] args) {
            // Initiate a new Scanner
            Scanner userInputScanner = new Scanner(System.in);
     
            // Testing nextLine();
            System.out.print("\nWhat is your name? ");
            String name = userInputScanner.nextLine();
     
            // Testing nextInt();
            System.out.print("How many cats do you have? ");
            int numberOfCats = userInputScanner.nextInt();
     
            // Testing nextDouble();
            System.out.print("How much money is in your wallet? $");
            double moneyInWallet = userInputScanner.nextDouble();
     
            System.out.println("\nHello " + name + "! You have " + numberOfCats
                    + (numberOfCats > 1 ? " cats" : " cat")
                    + " and $" + moneyInWallet + " in your wallet.\n");
        }
    }


이러한 코드가 있다고 하면 


이러한 오류가 뜨는 경우가 있다. 


이럴때의 해결책 >>>


컴파일시 javac (파일명).java - encoding (인코딩명)


ex) javac 1.java - encoding UTF8  << 인코딩 형식을 UTF-8 로 했을 경우


 출처:http://wookoa.tistory.com/55

■ 'javac'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다.

 

자바를 설치하고 환경변수를 설정하는 과정에서, 그 과정이 엇갈리거나 꼬이게 되면 흔히 볼 수 있는 에러 화면이다. 커맨드 입력창에 'javac' 명령을 날리면 볼 수 있는 메세지다."'javac'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다."본 포스팅에서는 이러한 에러를 해결하기 위한 방법을 소개한다.


 

 

 

 

 

 


 

 

 

자바 설치를 하고 열심히 환경변수를 설정한 뒤, 커맨드 입력창에 'javac' 명령을 날리자마자 아래와 같은 메세지를 받는다면 매우 당황스럽다. 보통은 환경변수 설정하는 단계에서 오타에 의한 실수인 경우도 존재하지만, Windows 7에서 Windows XP와 같은 방식으로 환경변수를 설정하게 되면 많이 발생하기도 한다.

 

 

 

만약 사용자 변수 PATH가 존재하지 않는다면 새로 생성한다. 이때 확인해야될 부분은 크게 두가지다. 첫번째는 환경 변수가 제대로 작성되었는지 검토해야 한다. 두번째는 JDK가 제대로 설치되었는지 확인한다. 설치한 소프트웨어가 JRE가 아닌, JDK가 확실하다면 javac.exe는 분명히 설치된 것이다.

 

인터넷에서 환경 변수를 설정하는 방법은 여러가지 존재한다. 하지만, 가장 교과서적인 방법은 JAVA_HOME 생성, CLASSPATH 생성, Path 수정 이 세 가지의 종류가 있다. 환경 변수 설정이 모두 끝났음에도 javac를 인식하지 못하고 위와 같은 메시지가 출력된다면, PC가%JAVA_HOME%을 인식하지 못하는 경우를 의심해 볼 필요가 있다. 이를 해결하기 위한 방법은 간단하다.

 

 

 

첫번째로 사용자 변수 PATH를 편집하여 변수 값 제일 앞에 %JAVA_HOME%\bin 설정한다. 만약 사용자 변수 PATH가 존재하지 않는다면 새로 생성한다.

 

 

 

두번째로 시스템 변수 Path의 %JAVA_HOME%을 실제 JDK 설치경로를 직접 설정한다.

 

 


+ Recent posts