How can I convert bits to bytes?

前端 未结 5 1080
無奈伤痛
無奈伤痛 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 12:40

    bool[] bools = ...
    BitArray a = new BitArray(bools);
    byte[] bytes = new byte[a.Length / 8];
    a.CopyTo(bytes, 0);
    

    EDIT: Actually this also returns:

    198 12 209 77 203 162 216 50 33 0 196 255 194 231 125 159
    

    Wrong endianness? I'll leave answer anyway, for reference.


    EDIT: You can use BitArray.CopyTo() by reversing the arrays like so:

    bool[] bools = ...
    Array.Reverse(bools); // NOTE: this modifies your original array
    BitArray a = new BitArray(bools);
    byte[] bytes = new byte[a.Length / 8];
    a.CopyTo(bytes, 0);
    Array.Reverse(bytes);
    

提交回复
热议问题