반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

디케이

자바: 10진수 > 2진수/8진수/16진수로 변환 + 대문자로출력 본문

Java

자바: 10진수 > 2진수/8진수/16진수로 변환 + 대문자로출력

디케이형 2020. 11. 26. 23:36
반응형

10진수를 2진수,8진수,16진수로 변환 할 때, Integer 클래스의 함수를 사용하면 쉽게 변환이 가능하다.

 

Integer 클래스의 toBinaryString, toOctalString, toHexString 함수를 사용하면 각각 2진수,8진수 16진수로 변환한다.

int i = 127;
 
String binaryString = Integer.toBinaryString(i); //2진수
String octalString = Integer.toOctalString(i);   //8진수
String hexString = Integer.toHexString(i);       //16진수
 
System.out.println(binaryString); //1111111
System.out.println(octalString);  //177
System.out.println(hexString);    //7f

 반대로 2진수,8진수,16진수를 10진수로 변환할 때에는 Integer 클래스의 parseInt를 사용하여 쉽게 변환이 가능하다.

int i = 127;
 
String binaryString = Integer.toBinaryString(i); //2진수
String octalString = Integer.toOctalString(i);   //8진수
String hexString = Integer.toHexString(i);       //16진수
 
System.out.println(binaryString); //1111111
System.out.println(octalString);  //177
System.out.println(hexString);    //7f
 
 
int binaryToDecimal = Integer.parseInt(binaryString, 2);
int binaryToOctal = Integer.parseInt(octalString, 8);
int binaryToHex = Integer.parseInt(hexString, 16);
 
System.out.println(binaryToDecimal); //127
System.out.println(binaryToOctal);   //127
System.out.println(binaryToHex);     //127

 

추가로 16진수를 대문자로 출력하기 위해서는 toUpperCase()를 사용하여 쉽게 가능하다.

System.out.println(Integer.toHexString(10).toUpperCase()); // A

 

반응형