Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python byte to "unsigned 8 bit integer"

Tags:

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?

like image 293
bbb Avatar asked Dec 11 '09 11:12

bbb


People also ask

What is an 8 bit unsigned 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.

How do you use unsigned int in Python?

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.

Does Python have unsigned int?

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.


2 Answers

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.

like image 127
codeape Avatar answered Oct 13 '22 00:10

codeape


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

like image 44
SilentGhost Avatar answered Oct 13 '22 01:10

SilentGhost