将 4 个整数打包为一个字节? [英] Packing 4 Integers as ONE BYTE?
问题描述
我有四个整数 {a
, b
, c
, d
} 可以有以下范围值:
I have four integers {a
, b
, c
, d
} that can have the following range of values:
a
- {0 或 1}(1 位)
a
- {0 or 1} (1 bit)
b
- {0 或 1}(1 位)
b
- {0 or 1} (1 bit)
c
- {0, 1, 2, ..., 7}(3 位)
c
- {0, 1, 2, ..., 7} (3 bits)
d
- {0, 1, 2, ..., 7}(3 位)
d
- {0, 1, 2, ..., 7} (3 bits)
首先,我想将它们打包成一个字节,然后可以写入二进制文件.稍后,我想解压该字节并将其转换为形式 (a
, b
, c
, >d
).
at first, I would like to pack them into a one byte that can be then written to a binary file.
later, I would like to unpack that one byte and get from it to a tuple of the form (a
, b
, c
, d
).
我知道如何在 python 中读/写一个字节到二进制文件.但是我如何进行位打包/解包?
I know how to read/write a byte to a binary file in python. But how do I do the bits packing/unpacking?
推荐答案
使用移位和按位或,然后转换为字符得到一个字节":
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
再来一次.
这篇关于将 4 个整数打包为一个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!