views:

371

answers:

3

hi i am reading in byte array/list from socket... but now i want python to treat the first byte as "unsigned 8 bit integer". how is this possible? and how is it possible to get its integer value as unsigned 8 bit integer?

thanks in advance!

+1  A: 

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

SilentGhost
for example, i have this in my server side codedata = 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?
bbb
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
SilentGhost
+3  A: 

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.

codeape
can you show how?
bbb
so what is stored in struct.unpack('B', data[0])[1]?
bbb
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.
codeape
In this case, it’s a tuple with one element, so struct.unpack('B', data[0])[1] will raise an IndexError. [http://stackoverflow.com/questions/1879914/decoding-packed-data-into-a-structure/1880563#1880563][Here] is an example of a typical use of struct.
A: 

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.