Reading 3 bytes as an integer

前端 未结 4 735
执笔经年
执笔经年 2021-02-13 10:16

How can I read 3 bytes as an integer?

Does struct module provide something like that?

I can read in 3 bytes and add an extra \\x00 and then interpret it as a 4-b

4条回答
  •  鱼传尺愫
    2021-02-13 11:10

    An alternative for python 2 and without the struct module would be:

    >>> s = '\x61\x62\xff'
    >>> a = sum([ord(b) * 2**(8*n) for (b, n) in zip(s, range(len(s))[::-1])])
    >>> print a
    6382335
    

    where the byte ordering is big-endian. This gives the same result as with unutbu answer:

    >>> print struct.unpack('>I', '\x00' + s)[0]
    6382335
    

    For little-endian byte ordering the conversion would be:

    >>> a = sum([ord(b) * 2**(8*n) for (b, n) in zip(s, range(len(s)))])
    >>> print a
    16736865
    >>> print struct.unpack('

提交回复
热议问题