23

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?

1
  • 2
    If you are willing to take a dependency on numpy, some of their functions take a dtype arg, which you can set to numpy.uint8. Example: bytestream = numpy.fromfile(infile, dtype=numpy.uint8) Commented Apr 23, 2015 at 21:13

3 Answers 3

23

Use the struct module.

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

We have to specify a range of 1 (0:1), because Python 3 converts automatically to an integer otherwise.

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

Also, have a look at this SO question.

Sign up to request clarification or add additional context in comments.

3 Comments

so what is stored in struct.unpack('B', data[0])[1]?
data[0] is the first byte that you receive. unpack("B", data[0]) treats that byte as a 8-bit unsigned integer (known as unsigned char in C) and returns a tuple containing that integer (had you passed two bytes to unpack you would do something like unpack("BB", data[0:2]) and get a 2-tuple back). The final [0] gets the first (and only) item in the tuple.
In this case, it’s a tuple with one element, so struct.unpack('B', data[0])[1] will raise an IndexError. [stackoverflow.com/questions/1879914/… is an example of a typical use of struct.
11

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".

3 Comments

for example, i have this in my server side code data = conn.recv(1000000) as long as i understand i receive bytes... so i want data[0] to be treated as "unsigned 8 bit integer". how is this possible?
This only works in Python 3.x. Python 2.6 has the b'string literal' syntax, but it is merely an alias for str, and older versions will give you a SyntaxError.
@musicinmybrain: that's why this question is tagged as python-3.x I guess
8

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.