How can I convert bits to bytes?

前端 未结 5 1081
無奈伤痛
無奈伤痛 2020-12-03 11:55

I have an array of 128 booleans that represent bits. How can I convert these 128 bit representations into 16 bytes?

Example:

I have an array that looks like

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 12:40

    The code is treating the first bit as the low bit of the word, so you end up with each word reversed. As a quick-and-dirty fix, try this:

    bytes[byteIndex] |= (byte)(1 << (7-bitIndex));
    

    That puts the first bit in the array at the highest position in the first byte, etc.

提交回复
热议问题