Ray Salemi
Ray Salemi

Reputation: 5913

Convert a byte to a negative integer?

I have a byte \ca that I want to convert to -54 not 202

Is there a function that does this or do I have to do this math in my code?

Here is my code:

    def load_sv_str(self, byte_str):
        byte_data = self.unpack_byte_data(byte_str)
        self.my_char = byte_data[0]

self.my_char keeps getting 202 when it should get -54

Upvotes: 1

Views: 309

Answers (2)

Bharel
Bharel

Reputation: 26900

You can use struct.unpack() like so:

>>> struct.unpack("b", b"\xca")[0]
-54

"b" is the format for a signed byte.

Upvotes: 0

Bharel
Bharel

Reputation: 26900

You can use int.from_bytes(). Make sure you use signed=True as it's a signed char:

>>> int.from_bytes(b"\xca", "little", signed=True)
-54

Upvotes: 4

Related Questions