【发布时间】:2015-01-04 18:04:28
【问题描述】:
为什么
struct.pack("!bbbb", 0x2, r, g, b)
当 r、g 或 b > 127 时,我的 python 代码失败?
我知道根据结构文档,“b”表示给定值的大小为 1 字节,但为什么它会因值超过 127 而失败?
【问题讨论】:
标签: python sockets struct.pack
为什么
struct.pack("!bbbb", 0x2, r, g, b)
当 r、g 或 b > 127 时,我的 python 代码失败?
我知道根据结构文档,“b”表示给定值的大小为 1 字节,但为什么它会因值超过 127 而失败?
【问题讨论】:
标签: python sockets struct.pack
根据the documentation,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'
【讨论】: