Packing 4 Integers as ONE BYTE?

前端 未结 4 1278
予麋鹿
予麋鹿 2020-12-16 13:35

I have four integers {a, b, c, d} that can have the following range of values:

a - {0 or 1} (1 bi

4条回答
  •  没有蜡笔的小新
    2020-12-16 14:18

    If you need to this kind of thing a lot then bit shifting can become tedious and error prone. There are third-party libraries that can help - I wrote one called bitstring:

    To pack and convert to a byte:

    x = bitstring.pack('2*uint:1, 2*uint:3', a, b, c, d).bytes
    

    and to unpack:

    a, b, c, d = bitstring.BitArray(bytes=x).unpack('2*uint:1, 2*uint:3')
    

    This is probably overkill for your example, but it's helpful when things get more complicated.

提交回复
热议问题