简体   繁体   English

在Python中模拟C#的sbyte(8位有符号整数)转换

[英]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

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: 我将使用Python标准库的struct模块,它经常用于将值转换为字节,反之亦然:

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

struct module can help you, eg here is a way to convert int(4 bytes) to 4 signed bytes 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)
>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM