Reputation: 31090
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]
Upvotes: 1
Views: 70
Reputation: 44980
You need to convert from byte
to char
if you plan to display numeric values as their corresponding ASCII character:
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. Arrays.toString()
exists only to print a sequence of elements.
Upvotes: 2