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


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...