如何制作所有Python3号码CTYPE.C_INT32?

发布于 2025-02-05 16:52:50 字数 295 浏览 1 评论 0原文

我正在尝试使用python3复制C程序行为,并反复将所有数字投入到CTYPES.C_INT32变得丑陋。

有什么办法可以默认python的int是ctypes.c_int32的实例?

编辑: 我想在多个C_INT32对象(例如XOR-ing和and-ing)之间执行算术操作,但是如果不添加.Value在每个C_TYPE INT对象后面,我就无法执行此操作。我想看看是否可以以某种方式覆盖默认的python int对象与ctypes中的c_int32更相似。

I am trying to replicate C program behaviours using Python3 and repeatedly casting all numbers to ctypes.c_int32 get ugly real fast.

Is there any way I could default Python's int to be an instance of ctypes.c_int32?

Edit:
I would like to perform arithmetic operations between multiple c_int32 objects (e.g. xor-ing and and-ing), but I can't do this without adding .value behind every c_type int object. I want to see if I can somehow override the default python int object to behave more similarly to c_int32 in ctypes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮惑 2025-02-12 16:52:50

您无法在Python 3中做您想做的事。

如果您只想将数学结果限制为签名的INT32结果ctypes不需要。以下截断n降低32位,然后调整符号位:

>>> def int32(n):
...   n &= (1<<32)-1
...   return n - (1<<32) if n & (1<<31) else n
...
>>> int32(-1)
-1
>>> int32(0x80000000)  # sign bit set (bit 31)
-2147483648
>>> int32(0x7fffffff)  # max positive int32
2147483647
>>> int32(0x7fffffff + 1)  # overflow to sign bit
-2147483648
>>> 1<<31         # without constraint
2147483648
>>> int32(1<<31)
-2147483648
>>> 1<<32         # without constraint
4294967296
>>> int32(1<<32)
0

You can't do what you want in Python 3. int in Python 2.3 and earlier (before int/long integration) worked they way I think you want.

If you just want to constrain math results to signed int32 results ctypes isn't needed. The following truncates n to the lower 32 bits, then adjusts for the sign bit:

>>> def int32(n):
...   n &= (1<<32)-1
...   return n - (1<<32) if n & (1<<31) else n
...
>>> int32(-1)
-1
>>> int32(0x80000000)  # sign bit set (bit 31)
-2147483648
>>> int32(0x7fffffff)  # max positive int32
2147483647
>>> int32(0x7fffffff + 1)  # overflow to sign bit
-2147483648
>>> 1<<31         # without constraint
2147483648
>>> int32(1<<31)
-2147483648
>>> 1<<32         # without constraint
4294967296
>>> int32(1<<32)
0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文