Backend/Java

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

퐁고 2023. 2. 12. 16:23
반응형

10진수 - decimal

  • 0~9까지의 수를 이용하고 그 수를 넘으면 높은 자릿 수를 1씩 증가시켜 숫자를 나타냄
  • ex) 69

2진수 - binary

  • 0~1까지의 수를 이용하여 숫자를 나타냄
  • ex) 1000101

8진수 - octal

  • 0~7까지의 수를 이용하여 숫자를 나타냄
  • ex) 105 → 8x8(1) + 8 x 8(0) + 1 x 5

16진수 - hexa

  • 0~9까지의 수, A~F까지의 6개의 문자를 이용해 숫자를 나타냄
  • 45 → 16 x 4 + 1 x 5

 

// 숫자 123의 변환, 2진수 0b, 8진수는 0, 16진수는 0x를 붙여준다.
int decimal = 123;
int binary = 0b1111011;
int octal = 0173;
int hexa = 0x7B;

System.out.println(decimal);
        System.out.println(binary);
        System.out.println(octal);
        System.out.println(hexa);

// 10진수를 2진수, 8진수, 16진수로 문자열 형식으로 변환
String binaryS = Integer.toBinaryString(decimal);
String octalS = Integer.toOctalString(decimal);
String hexaS = Integer.toHexString(decimal);
// 10진수로 변환
int decimalS = Integer.parseInt(octalS);

System.out.println(binaryS);
System.out.println(octalS);
System.out.println(hexaS);
System.out.println(decimalS);