Search code examples
pythonpython-3.xsigned

How to convert bytes byte by byte to signed int


I have a bytes element. My word size is 1, a single byte. The contents can be b'\xff\xff\x01' meaning [-1, -1, 1].

I want to convert it to the int representation from the bytes form. Logically my attempt is:

ints = [int.from_bytes(j, byteorder='little', signed=True) for j in b'\xff\xff\x01']

TypeError: cannot convert 'int' object to bytes

However this does not work as the for j in bytes() converts a bytes element directly into an int j. This is however an unsigned conversion, I need signed. How do I convert my bytes, byte by byte, into a signed integer.


Solution

  • Another way, using Numpy:

    >>> import numpy as np
    >>> np.frombuffer(b'\xff\xff\x01', dtype=np.int8)
    array([-1, -1,  1], dtype=int8)