問題描述
例如,一個字節B
中的位是10000010
,我怎樣才能將這些位從字面上分配給字符串str
,即, 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
(a) 當位以(最左邊的)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
推薦答案
使用整數#toBinaryString()
:
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
演示.
這篇關于如何將字節轉換為其二進制字符串表示形式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!