如何将字节转换成它的二进制字符串重新presentation [英] How to convert a byte to its binary string representation
问题描述
例如,在一个字节 B
的位 10000010
,我怎么可以指定位串 STR
从字面上看,就是海峡=10000010
。
For example, the bits in a byte B
are 10000010
, how can I assign the bits to the string str
literally, that is, str = "10000010"
.
修改
我从一个二进制文件中读取字节,并将其存储于字节数组中 B
。我使用的System.out.println(Integer.toBinaryString(B [i]))
。问题是
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
(一)当用位(最左边)开始1,因为它转换 B [I]
来负int值的输出是不正确的。
(a) when the bits begin with (leftmost) 1, the output is not correct because it converts B[i]
to a negative int value.
(b)如位与 0
开始,输出忽略 0
,例如,假设 B [0]
有00000001,输出为 1
而不是 00000001
(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
推荐答案
使用<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString%28int%29\"><$c$c>Integer#toBinaryString()$c$c>:
byte b1 = (byte) 129;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
System.out.println(s1); // 10000001
byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println(s2); // 00000010
DEMO.
这篇关于如何将字节转换成它的二进制字符串重新presentation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!