In C#, I can cast things to 8bit signed ints like so:
(sbyte)arg1;
which when arg1 = 2, the cast returns 2 also. However, obviously casting 128 will return -128. More specifically casting 251 will return -5.
What's the best way to emulate this behavior?
Edit: Found a duplicate question: Typecasting in Python
s8 = (i + 2**7) % 2**8 - 2**7 // convert to signed 8-bit
With ctypes:
from ctypes import cast, pointer, c_int32, c_byte, POINTER
cast(pointer(c_int32(arg1)), POINTER(c_byte)).contents.value
I'd use the struct module of the Python standard library, which, as so often, comes in handy for turning values into bytes and viceversa:
>>> def cast_sbyte(anint):
return struct.unpack('b', struct.pack('<i', anint)[0])[0]
... ...
>>> cast_sbyte(251)
-5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With