gjossep
gjossep

Reputation: 23

Convert a array having bits into one byte

I m trying to convert 8 bits into one byte. The way the bits are represented are by using a byte object that only contains a 1 or a 0.

If i have a 8 length byte array with these bits, how can i convert them into one byte.

public byte bitsToByte(byte[] bits) {
 //Something in here. Each byte inside bits is either a 1 or a 0.
}

Can anyone help?

Thanks

Upvotes: 0

Views: 605

Answers (2)

YoungHobbit
YoungHobbit

Reputation: 13402

left shift by 1 first for each bit in the array and then add the bit to the byte.

The implementation is based on the assumption that first bit in the array is sign bit and following bits are the magnitude in higher to lower positions of the byte.

public byte bitsToByte(byte[] bits) {
  byte value = 0;
  for (byte b : bits) {
    value <<=1;
    value += b;
  }
  return value;
}

Test the method:

public static void main(String[] args) {
  BitsToByte bitsToByte = new BitsToByte();
  byte bits[] = new byte[]{0,0,1,0,1,1,0,1};  // 1 + 0 + 4 + 8 + 0 + 32 + 0 + 0
  byte value = bitsToByte.bitsToByte(bits);
  System.out.println(value);
}

output:

45

Covert the byte array into a byte value (in the same order):

public static byte bitsToByte1(byte[] bits){
  byte result = 0;
  for (byte i = 0; i < bits.length; i++) {
    byte tmp = bits[i];
    tmp <<= i;             // Perform the left shift by "i" times. "i" position of the bit
    result |= tmp;         // perform the bit-wise OR 
  }
  return result;
}

input: (same array in reverse)

  byte bits1[] = new byte[]{1,0,1,1,0,1,0,0};
  value = bitsToByte1(bits1);
  System.out.println(value);

output:

45

Upvotes: -1

John E.
John E.

Reputation: 418

public static byte bitsToByte(byte[] bits){
    byte b = 0;
    for (int i = 0; i < 8; i++)
        b |= (bits[i]&1) << i;
    return b;
}

//as an added bonus, the reverse.
public static byte[] bitsToByte(byte bits){
    byte[] b = new byte[8];
    for (int i = 0; i < 8; i++)
        b[i] = (byte) ((bits&(1 << i)) >>> i);
    return b;
}

Upvotes: 3

Related Questions