16

我试图将一个函数从 C 移植到 Python 并使其易于调试,我希望它执行相同的 CPU 字长限制操作,以便我可以比较中间结果。换句话说,我想要这样的东西:

a = UnsignedBoundedInt(32, 399999)
b = UnsignedBoundedInt(32, 399999)
print(a*b) # prints 1085410049 (159999200001 % 2**32)

实现这一点的最佳方法是什么,以便所有操作(包括按位移位)都可以像在 C 中一样工作?

4

2 回答 2

23

您可以尝试使用ctypes.uint_32为您绑定结果:

>>> import ctypes
>>> print ctypes.c_uint32(399999 * 399999).value
1085410049

或者,您可以使用numpy的数据类型:

>>> import numpy as np
>>> a = np.uint32(399999)
>>> b = np.uint32(399999)
>>> a * b
__main__:1: RuntimeWarning: overflow encountered in uint_scalars
1085410049
于 2013-10-07T19:38:02.767 回答
3

这是一个有趣的解决方案,尽管它只适用于 Python 2:

class U32:
    """Emulates 32-bit unsigned int known from C programming language."""

    def __init__(self, num=0, base=None):
        """Creates the U32 object.

        Args:
            num: the integer/string to use as the initial state
            base: the base of the integer use if the num given was a string
        """
        if base is None:
            self.int_ = int(num) % 2**32
        else:
            self.int_ = int(num, base) % 2**32

    def __coerce__(self, ignored):
        return None

    def __str__(self):
        return "<U32 instance at 0x%x, int=%d>" % (id(self), self.int_)

    def __getattr__(self, attribute_name):
        print("getattr called, attribute_name=%s" % attribute_name)
        # you might want to take a look here:
        # https://stackoverflow.com/q/19611001/1091116
        r = getattr(self.int_, attribute_name)
        if callable(r):  # return a wrapper if integer's function was requested
            def f(*args, **kwargs):
                if args and isinstance(args[0], U32):
                    args = (args[0].int_, ) + args[1:]
                ret = r(*args, **kwargs)
                if ret is NotImplemented:
                    return ret
                if attribute_name in ['__str__', '__repr__', '__index__']:
                    return ret
                ret %= 2**32
                return U32(ret)
            return f
        return r

print(U32(4) / 2)
print(4 / U32(2))
print(U32(4) / U32(2))

有关 Python 3 的兼容性,请查看此处

于 2013-12-06T18:05:50.760 回答