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 unsigned 8 bit integer?
An 8-bit unsigned integer has a range of 0 to 255, while an 8-bit signed integer has a range of -128 to 127 - both representing 256 distinct numbers.
Compared to C programming, Python does not have signed and unsigned integers as data types. There is no need to specify the data types for variables in python as the interpreter itself predicts the variable data type based on the value assigned to that variable.
Python doesn't have builtin unsigned types. You can use mathematical operations to compute a new int representing the value you would get in C, but there is no “unsigned value” of a Python int. The Python int is an abstraction of an integer value, not a direct access to a fixed-byte-size integer.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With