简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM