Home > Software design >  Convert a byte to a negative integer?
Convert a byte to a negative integer?

Time:01-17

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

CodePudding user response:

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

CodePudding user response:

You can use struct.unpack() like so:

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

"b" is the format for a signed byte.

  •  Tags:  
  • Related