Skip to content

How to convert a single byte from a bytearray to singed int

I have a bytearray which consist of 4 bytes where each byte represents a singed byte in the range of -128..127. How to convert this?

The byte-array representing the values: -1, 15, 1 and -2 is created by:

data = bytearray()
data.extend([0xff, 0x0f, 0x01, 0xfe])

Now I try to convert it with this code:

import struct
my_signed_byte_0 = struct.unpack("b", data[0])[0]
my_signed_byte_1 = struct.unpack("b", data[1])[0]
my_signed_byte_2 = struct.unpack("b", data[2])[0]
my_signed_byte_3 = struct.unpack("b", data[3])[0]

This raises error:

TypeError: a bytes-like object is required, not ‘int’

This happens, because data[0] does return an int and not a bytearray.



Since bytearray objects are sequences of integers (akin to a list), for a bytearray object b, b[0] will be an integer, while b[0:1] will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

my_signed_byte_0 = struct.unpack("b", data[0:1])[0]
my_signed_byte_1 = struct.unpack("b", data[1:2])[0]
my_signed_byte_2 = struct.unpack("b", data[2:3])[0]
my_signed_byte_3 = struct.unpack("b", data[3:4])[0]
User contributions licensed under: CC BY-SA
8 People found this is helpful