[英]Simulating C#'s sbyte (8 bit signed integer) casting in Python
In C#, I can cast things to 8bit signed ints like so: 在C#中,我可以将内容转换为8位签名的内容,如下所示:
(sbyte)arg1;
which when arg1 = 2
, the cast returns 2 also. 当
arg1 = 2
,演员也返回2。 However, obviously casting 128
will return -128
. 但是,显然铸造
128
将返回-128
。 More specifically casting 251
will return -5
. 更具体地,铸件
251
将返回-5
。
What's the best way to emulate this behavior? 模仿这种行为的最佳方法是什么?
Edit: Found a duplicate question: Typecasting in Python 编辑:发现一个重复的问题: 在Python中进行类型转换
s8 = (i + 2**7) % 2**8 - 2**7 // convert to signed 8-bit
With ctypes: 使用ctypes:
from ctypes import cast, pointer, c_int32, c_byte, POINTER
cast(pointer(c_int32(arg1)), POINTER(c_byte)).contents.value
>>> from numpy import int8
>>> int8(251)
-5
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.