2

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)
7
  • Are those examples of real values? If so use a byte array instead. Commented Mar 20, 2017 at 21:09
  • 3
    Use a BitSet? Commented Mar 20, 2017 at 21:10
  • 2
    How do you want the bits encoded? 1010110101 -> 0b10101101 0b01000000 = 0xAD 0x40? Or maybe 0b1010110101 -> 0b10110101 00000010 = 0xB5 0x02? Commented Mar 20, 2017 at 21:10
  • I'm making an compression algorithm, so sometimes the bits are not divisible by 8. Commented Mar 20, 2017 at 21:12
  • 1010110101 -> 10101101 01000000 Commented Mar 20, 2017 at 21:14

1 Answer 1

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();
}
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.