[英]How to convert between byte and bit arrays with Java?
I have the following code trying to convert between byte and bit arrays, somehow it's not converting correctly, what is wrong and how to correct it ? 我有以下代码尝试在字节和位数组之间转换,以某种方式无法正确转换,什么是错误的,以及如何纠正它?
String getBitsFromBytes(byte[] Byte_Array) // 129
{
String Bits="";
for (int i=0;i<Byte_Array.length;i++) Bits+=String.format("%8s",Integer.toBinaryString(Byte_Array[i] & 0xFF)).replace(' ','0');
System.out.println(Bits); // 10000001
return Bits;
}
byte[] getBytesFromBits(int[] bits)
{
byte[] results=new byte[(bits.length+7)/8];
int byteValue=0;
int index;
for (index=0;index<bits.length;index++)
{
byteValue=(byteValue<<1)|bits[index];
if (index%8==7) results[index/8]=(byte)byteValue;
}
if (index%8!=0) results[index/8]=(byte)((byte)byteValue<<(8-(index%8)));
System.out.println(Arrays.toString(results));
return results;
}
...
String bit_string=getBitsFromBytes("ab".getBytes()); // 0110000101100010 : 01100001 + 01100010 --> ab
int[] bits=new int[bit_string.length()];
for (int i=0;i<bits.length;i++) bits[i]=Integer.parseInt(bit_string.substring(i,i+1));
getBytesFromBits(bits);
When I ran it, I got the following : 当我运行它时,得到以下信息:
0110000101100010
[97, 98]
I was expecting this : 我期望这样:
0110000101100010
[a, b]
You need to convert from byte
to char
if you plan to display numeric values as their corresponding ASCII character: 如果计划将数值显示为相应的ASCII字符,则需要从
byte
转换为char
:
char[] chars = new char[results.length];
for (int i = 0; i < results.length; i++) {
chars[i] = (char) results[i];
}
System.out.println(Arrays.toString(chars));
To convert from byte[]
to String
you should use new String(byte[])
constructor and specify the right charset. 要将
byte[]
转换为String
,应使用new String(byte[])
构造函数并指定正确的字符集。 Arrays.toString()
exists only to print a sequence of elements. Arrays.toString()
仅用于打印一系列元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.