我该怎么做才能让 python 像 c 一样使用补码来解释位
what can i do to let python use complement code to interpret bits just like c do
其实我只是想让Python和c做一样的事情
例如,在 c:
int num = 1 << 31; // num's bits should be 0x8000 0000.
printf("%d\n", num); // the print is -2147483648, because of complememnt.
然而,在 Python:
>>> num = 1 << 31
>>> print num
2147483648
>>> print int.bit_length(num)
32
>>> print '{0:b}'.format(num)
10000000000000000000000000000000
似乎Python使用真正的代码来解释数字。我该怎么做才能让 python 像 c 一样使用补码来解释位。
使用 ctypes
模块您可以获得您正在寻找的结果:
import ctypes
ctypes.c_int(1 << 31)
我希望这足以满足您接下来要使用此整数执行的操作。 Python 比使用整数的 C 更宽容:它甚至可以通过在需要保存操作结果时升级到更大的表示形式(例如 int 到 long)来避免溢出。很高兴有更好的抽象,但在较低级别时确实会使事情复杂化。
其实我只是想让Python和c做一样的事情
例如,在 c:
int num = 1 << 31; // num's bits should be 0x8000 0000.
printf("%d\n", num); // the print is -2147483648, because of complememnt.
然而,在 Python:
>>> num = 1 << 31
>>> print num
2147483648
>>> print int.bit_length(num)
32
>>> print '{0:b}'.format(num)
10000000000000000000000000000000
似乎Python使用真正的代码来解释数字。我该怎么做才能让 python 像 c 一样使用补码来解释位。
使用 ctypes
模块您可以获得您正在寻找的结果:
import ctypes
ctypes.c_int(1 << 31)
我希望这足以满足您接下来要使用此整数执行的操作。 Python 比使用整数的 C 更宽容:它甚至可以通过在需要保存操作结果时升级到更大的表示形式(例如 int 到 long)来避免溢出。很高兴有更好的抽象,但在较低级别时确实会使事情复杂化。