Convert Python byte to “unsigned 8 bit integer”

前端 未结 3 1340
执念已碎
执念已碎 2020-12-16 11:22

I am reading in a byte array/list from socket. I want Python to treat the first byte as an \"unsigned 8 bit integer\". How is it possible to get its integer value as an un

相关标签:
3条回答
  • 2020-12-16 11:59

    bytes/bytearray is a sequence of integers. If you just access an element by its index you'll have an integer:

    >>> b'abc'
    b'abc'
    >>> _[0]
    97
    

    By their very definition, bytes and bytearrays contain integers in the range(0, 256). So they're "unsigned 8-bit integers".

    0 讨论(0)
  • 2020-12-16 12:07

    Use the struct module.

    import struct
    value = struct.unpack('B', data[0])[0]
    

    Note that unpack always returns a tuple, even if you're only unpacking one item.

    Also, have a look at this SO question.

    0 讨论(0)
  • 2020-12-16 12:22

    Another very reasonable and simple option, if you just need the first byte’s integer value, would be something like the following:

    value = ord(data[0])
    

    If you want to unpack all of the elements of your received data at once (and they’re not just a homogeneous array), or if you are dealing with multibyte objects like 32-bit integers, then you’ll need to use something like the struct module.

    0 讨论(0)
提交回复
热议问题