程式扎記: [ Java 常見問題 ] How to convert a byte to its binary string representation

標籤

2016年8月24日 星期三

[ Java 常見問題 ] How to convert a byte to its binary string representation

Source From Here
Question
I read the byte from a binary file, and stored in the byte array B. I use System.out.println(Integer.toBinaryString(B[i])). the problem is:
(a) when the bits begin with (leftmost) 1, the output is not correct because it converts B[i] to a negative int value.
(b) if the bits begin with 0, the output ignore 0, for example, assume B[0] has 00000001, the output is 1 instead of 00000001


How-To
Use Integer#toBinaryString():
  1. byte b1 = (byte129;  
  2. String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ''0');  
  3. System.out.println(s1); // 10000001  
  4.   
  5. byte b2 = (byte2;  
  6. String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ''0');  
  7. System.out.println(s2); // 00000010  
Or you can leverage exist library flib:
  1. package test;  
  2.   
  3. import flib.util.HexByteKit;  
  4.   
  5. public class Test {  
  6.   
  7.     public static void main(String[] args) {  
  8.         byte b1[] = {(byte129};  
  9.         System.out.printf("%s\n", HexByteKit.Byte2Bin(b1));  
  10.   
  11.         byte b2[] = {(byte2};  
  12.         System.out.printf("%s\n", HexByteKit.Byte2Bin(b2));               
  13.     }  
  14. }  
Execution result:
10000001
00000010


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!