且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 4 个整数打包为一个字节?

更新时间:2023-02-04 12:37:18

使用移位和按位或,然后转换为字符得到一个字节":

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

解释:最初,你有

0000000a
0000000b
00000ccc
00000ddd

左移给你

0000000a
000000b0
000ccc00
ddd00000

按位 OR 结果

dddcccba

转换为字符会将其转换为单个字节.

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

拆包:四种不同的右移结果

Unpacking: The four different right-shifts result in

dddcccba
0dddcccb
00dddccc
00000ddd

使用 1 (0b00000001) 或 7 (0b00000111) 屏蔽(按位与)结果>

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

0000000a
0000000b
00000ccc
00000ddd

再来一次.