1

How can i convert the following bit array to a byte array?

int[] bits = new int[]{1, 0, 1, 0, 1, 1, 0, 1, 0, 1};

The bits should be mapped to bytes as follows:

1010110101 -> 10101101 01000000 (0xAD 0x40)
Jason
  • 11,744
  • 3
  • 42
  • 46
  • Are those examples of real values? If so use a byte array instead. – cyroxis Mar 20 '17 at 21:09
  • 3
    Use a `BitSet`? – Kayaman Mar 20 '17 at 21:10
  • 2
    How do you want the bits encoded? `1010110101` -> `0b10101101 0b01000000` = `0xAD 0x40`? Or maybe `0b1010110101` -> `0b10110101 00000010` = `0xB5 0x02`? – Andreas Mar 20 '17 at 21:10
  • I'm making an compression algorithm, so sometimes the bits are not divisible by 8. –  Mar 20 '17 at 21:12
  • 1010110101 -> 10101101 01000000 –  Mar 20 '17 at 21:14
  • What trouble do you have writing the code? If you're good enough to write your own bit-level compression algorithm, you should be well-versed enough in [Java bit-manipulation](http://stackoverflow.com/q/6250114/5221149) to do this. – Andreas Mar 20 '17 at 21:16
  • A BitSet would store the bits in the wrong order (different to the OPs requirements). – Jason Mar 20 '17 at 23:54

1 Answers1

2
public class TestBitToByteEncoder {

    public static void main(String[] args) {
        int[] bits = new int[]{1, 0, 1, 0, 1, 1, 0, 1, 0, 1};
        byte[] bytes = encodeToByteArray(bits);
    }

    private static byte[] encodeToByteArray(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) byteValue << (8 - (index % 8));
        }

        return results;
    }
}

Edit: If you are happy to store the bits in the opposite order within bytes:

private static byte[] encodeToByteArray(int[] bits) {
    BitSet bitSet = new BitSet(bits.length);
    for (int index = 0; index < bits.length; index++) {
        bitSet.set(index, bits[index] > 0);
    }

    return bitSet.toByteArray();
}
Jason
  • 11,744
  • 3
  • 42
  • 46