Simulating C # sbyte (8-bit signed integer) in Python

In C #, I can distinguish things from 8-bit signed ints like this:

(sbyte)arg1;

which arg1 = 2also returns 2. However, it is obvious that casting 128will return -128. More specifically, casting 251will return -5.

What is the best way to imitate this behavior?

Edit: duplicate question found: Typecasting in Python

s8 = (i + 2**7) % 2**8 - 2**7      // convert to signed 8-bit
+3
source share
5 answers

With ctypes:

from ctypes import cast, pointer, c_int32, c_byte, POINTER
cast(pointer(c_int32(arg1)), POINTER(c_byte)).contents.value
+3
source

I would use the structPython standard library module, which is so useful for turning values ​​into bytes and vice versa:

>>> def cast_sbyte(anint):
    return struct.unpack('b', struct.pack('<i', anint)[0])[0]
... ... 
>>> cast_sbyte(251)
-5
+2
source

struct , . int (4 ) 4

>>> import struct
>>> struct.pack('i',251)
'\xfb\x00\x00\x00'
>>> s=struct.pack('i',251)
>>> print struct.unpack('bbbb',s)
(-5, 0, 0, 0)
0
>>> from numpy import int8
>>> int8(251)
-5
0

Try one of the following:

>>> sbyte=lambda n:(255 & n^128)-128 
>>> # or sbyte=lambda n:(n+128 & 255)-128

>>> sbyte(251)
-5
>>> sbyte(2)
2
0
source

Source: https://habr.com/ru/post/1754071/


All Articles