1

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]
2
  • What exactly is a bit array? Are you referring to Java's BitSet? Commented Feb 28, 2019 at 17:41
  • 5
    I think you got what you were expecting, 97 is the ascii number for a, and 98 is ascii number for b. missing a cast? Commented Feb 28, 2019 at 17:44

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.