0

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.

YBrush
  • 310
  • 1
  • 10
  • Does this answer your question? [How to get a single byte in a string of bytes, without converting to int](https://stackoverflow.com/questions/34716876/how-to-get-a-single-byte-in-a-string-of-bytes-without-converting-to-int) – mkrieger1 Oct 07 '22 at 11:01
  • 1
    But if you have 4 bytes, you could just use `struct.unpack("bbbb", data)`. – mkrieger1 Oct 07 '22 at 11:03
  • It's not clear what you are trying to do here. Why use `struct.unpack` if `data[0]` is already an int? Your question says you want to convert it *to* an int, but the error says you already have one. – kaya3 Oct 07 '22 at 11:03
  • 1
    @kaya3 Because `data[0]` is the wrong int. – mkrieger1 Oct 07 '22 at 11:03
  • If the question is just how to get an int into the range -128 to 127, you can write `x if x <= 127 else x - 256`. – kaya3 Oct 07 '22 at 11:05

1 Answers1

1

https://docs.python.org/3/library/stdtypes.html?highlight=bytearray#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]
YBrush
  • 310
  • 1
  • 10
Raibek
  • 558
  • 3
  • 6