어제 오늘 내일

[Java] 10진수 <-> 2진수, 8진수, 16진수로 변환하기 본문

IT/Java

[Java] 10진수 <-> 2진수, 8진수, 16진수로 변환하기

hi.anna 2021. 4. 24. 22:11

 

10진수 -> 2진수, 8진수, 16진수로 변환하기

java.lang.Integer의 toBinaryString(), toOctalString(), toHexaString() 메소드를 이용하여

10진수를 2진수, 8진수, 16진수 문자열로 변환할 수 있습니다.

 

리턴 타입 클래스 메소드 설명
static String java.lang.Integer toBinaryString(int i) 10진수 -> 2진수
static String java.lang.Integer toOctalString(int i) 10진수 -> 8진수
static String java.lang.Integer toHexaString(int i) 10진수 -> 16진수

 

 예제 

public class NumberConvert {
    public static void main(String[] args) {
        int decimal = 10;

        String binary = Integer.toBinaryString(decimal); // 10진수 -> 2진수
        String octal = Integer.toOctalString(decimal); // 10진수 -> 8진수
        String hexaDecimal = Integer.toHexString(decimal); // 10진수 -> 16진수

        System.out.println("10진수 : " + decimal);
        System.out.println("2진수 : " + binary);
        System.out.println("8진수 : " + octal);
        System.out.println("16진수 : " + hexaDecimal);
    }
}

 

 결과 

10진수 : 10
2진수 : 1010
8진수 : 12
16진수 : a

위 코드는 10진수 10을 

2진수, 8진수, 16진수로 변환하고 있습니다.

 

 

 

2진수, 8진수, 16진수 -> 10진수

java.lang.Integer 클래스의 parseInt() 메소드를 이용하여

2진수, 8진수, 16진수 문자열을 10진수 integer로 변경할 수 있습니다.

 

리턴 타입 클래스 메소드 설명
static int java.lang.Integer parseInt(String s) 문자열(s)을 10진수로 읽어서
int로 반환합니다.
static int java.lang.Integer parseInt(String s, int radix) 문자열(s)을 변환할 진수(radix)로 읽어서
int로 반환합니다.
(따라서, 2번째 파라미터(radix)를 10으로 입력하면, parseInt(String s)와 같습니다.)

 

 예제 

public class NumberConvert {
    public static void main(String[] args) {

        int binaryToDecimal = Integer.parseInt("1010", 2);
        int octalToDecimal = Integer.parseInt("12", 8);
        int hexaToDecimal = Integer.parseInt("A", 16);

        System.out.println("2진수(1010) -> 10진수 : " + binaryToDecimal); // 10
        System.out.println("8진수(12) -> 10진수 : " + octalToDecimal); // 10
        System.out.println("16진수(a) -> 10진수 : " + hexaToDecimal); // 10

    }
}

 

 결과 

2진수(1010) -> 10진수 : 10
8진수(12) -> 10진수 : 10
16진수(a) -> 10진수 : 10

위 코드는 2진수, 8진수, 16진수를 10진수로 변환하고 있습니다.

 

 

반응형
Comments