如何限制Python中整数变量的位数?
我想在Python中实现IDEA算法。在Python里,变量的大小没有限制,但我需要限制整数的位数,比如说,要进行循环左移操作。你有什么建议吗?
4 个回答
2
这个 bitstring 模块可能会对你有帮助(文档可以在 这里 找到)。下面这个例子创建了一个22位的比特串,并将比特向右旋转了3位:
>>> from bitstring import BitArray
>>> a = BitArray(22) # creates 22-bit zeroed bitstring
>>> a.uint = 12345 # set the bits with an unsigned integer
>>> a.bin # view the binary representation
'0b0000000011000000111001'
>>> a.ror(3) # rotate to the right
>>> a.bin
'0b0010000000011000000111'
>>> a.uint # and back to the integer representation
525831
2
这是一个8位的掩码,进行循环左移:
shifted = number << 1
overflowed = (number & 0x100) >> 8
shifted &= 0xFF
result = overflowed | shifted
你可以创建一个类来帮你完成这个操作。如果再加一点相似的代码,它还可以处理任意大小的值,进行任意数量的移位。
3
一种方法是使用BitVector这个库。
使用示例:
>>> from BitVector import BitVector
>>> bv = BitVector(intVal = 0x13A5, size = 32)
>>> print bv
00000000000000000001001110100101
>>> bv << 6 #does a cyclic left shift
>>> print bv
00000000000001001110100101000000
>>> bv[0] = 1
>>> print bv
10000000000001001110100101000000
>>> bv << 3 #cyclic shift again, should be more apparent
>>> print bv
00000000001001110100101000000100