Packing 4 Integers as ONE BYTE?

前端 未结 4 1273
予麋鹿
予麋鹿 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:34

    Use shift and bitwise OR, then convert to a character to get a "byte":

    x = chr(a | (b << 1) | (c << 2) | (d << 5))
    

    To unpack this byte again, first convert to an integer, then shift and use bitwise AND:

    i = ord(x)
    a = i & 1
    b = (i >> 1) & 1
    c = (i >> 2) & 7
    d = (i >> 5) & 7
    

    Explanation: Initially, you have

    0000000a
    0000000b
    00000ccc
    00000ffffd
    

    The left-shifts give you

    0000000a
    000000b0
    000ccc00
    ffffd00000
    

    The bitwise OR results in

    ffffdcccba
    

    Converting to a character will convert this to a single byte.

    Unpacking: The four different right-shifts result in

    ffffdcccba
    0ffffdcccb
    00ffffdccc
    00000ffffd
    

    Masking (bitwise AND) with 1 (0b00000001) or 7 (0b00000111) results in

    0000000a
    0000000b
    00000ccc
    00000ffffd
    

    again.

提交回复
热议问题