Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating C#'s sbyte (8 bit signed integer) casting in Python

Tags:

python

c#

casting

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
like image 679
Dominic Bou-Samra Avatar asked Mar 12 '26 07:03

Dominic Bou-Samra


2 Answers

With ctypes:

from ctypes import cast, pointer, c_int32, c_byte, POINTER
cast(pointer(c_int32(arg1)), POINTER(c_byte)).contents.value
like image 184
Matthew Flaschen Avatar answered Mar 13 '26 19:03

Matthew Flaschen


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
like image 27
Alex Martelli Avatar answered Mar 13 '26 19:03

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!