为什么
struct.pack("!bbbb", 0x2, r, g, b)
当 r、g 或 b > 127 时,我的 Python 代码失败?
我知道“b”表示根据结构文档,给定值的大小为 1 个字节,但为什么它会因值超过 127 而失败?
最佳答案
根据the documentation ,b
代表:
signed char
表示其有效范围是[-128, 127]。这就是错误消息明确指出的内容:
>>> struct.pack("!bbbb", 0x2, 127, 127, 128)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: byte format requires -128 <= number <= 127
使用B
不会产生错误:
>>> struct.pack("!bbbB", 0x2, 127, 127, 128)
'\x02\x7f\x7f\x80'
关于python - struct.pack() 因 int > 127 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26809855/