为什么是
struct.pack("!bbbb", 0x2, r, g, b)
当 r、g 或 b > 127 时,我的 python 代码失败?
我知道根据结构文档,“b”表示给定值的大小为 1 个字节,但为什么它会因超过 127 的值而失败?
为什么是
struct.pack("!bbbb", 0x2, r, g, b)
当 r、g 或 b > 127 时,我的 python 代码失败?
我知道根据结构文档,“b”表示给定值的大小为 1 个字节,但为什么它会因超过 127 的值而失败?
根据文档,b
代表:
签名字符
这意味着它的有效范围是 [-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'