프로그래밍/Java,JSP

int를 이진 문자열로 변환(convert int to bit-binary string)

채윤아빠 2020. 10. 15. 21:29
728x90
반응형

 

0x1B 바이트를 이진 문자열로 변환하면 "00011011"로 표현됩니다.

이를 자바에서 처리하려면, 아래와 같이 Integer.toBinaryString() 메소드를 이용하면 됩니다.


System.out.println(Integer.toBinaryString(0x1B))

/* 실행결과
11011
*/

위 코드를 실행하면, "11011"만 출력됩니다. toBinaryString() 메소드는 앞의 "0" 문자열을 제외하고, 변환하여 주기 때문입니다. 8자리 바이트로 맞추려면, String.format() 메소드를 이용하여 자리수를 채워지고, replace() 메소드로 공백을 "0"으로 바꾸어 주면 됩니다.


System.out.println(String.format("%8s", Integer.toBinaryString(0x1B)).replace(" ", "0"))

/* 실행결과
00011011
*/

위 코드를 실행하면 "00011011"로 출력됩니다.

비트 자리수에 맞게 String.format() 함수를 이용하면, 이진 문자열의 앞자리 0을 맞추어 채울 수 있습니다.


System.out.println(String.format("%16s", Integer.toBinaryString(word)).replace(" ", "0"))

/* 실행결과
0000000000011011
*/

System.out.println(String.format("%32s", Integer.toBinaryString(doubleWord)).replace(" ", "0"))
/* 실행결과
00000000000110110000000000011011
*/