gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:46 25 4
gpt4 key购买 nike

在 C# 中,我可以像这样将内容转换为 8 位有符号整数:

(sbyte)arg1;

arg1 = 2 时,转换也返回 2。但是,显然转换 128 将返回 -128。更具体地说,转换 251 将返回 -5

模拟此行为的最佳方式是什么?

编辑:发现重复问题:Typecasting in Python

s8 = (i + 2**7) % 2**8 - 2**7      // convert to signed 8-bit

最佳答案

使用 ctypes:

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

关于c# - 在 Python 中模拟 C# 的 sbyte(8 位有符号整数)转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3222088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com