【问题标题】:struct.pack() failing with int > 127struct.pack() 失败,int > 127
【发布时间】: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


    【解决方案1】:

    根据the documentationb代表:

    签名字符

    这意味着它的有效范围是[-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'
    

    【讨论】:

      猜你喜欢
      • 2014-11-10
      • 2018-10-08
      • 1970-01-01
      • 2019-05-02
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      相关资源
      最近更新 更多