如何限制Python中整数变量的位数?

时间:2010-11-16 19:02:34

标签: python algorithm cryptography

我想在Python中实现IDEA算法。在Python中,我们对可变大小没有限制,但我需要在整数中限制位数,例如,进行循环左移。你有什么建议吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

具有循环左移的8位掩码:

shifted = number << 1
overflowed = (number & 0x100) >> 8
shifted &= 0xFF
result = overflowed | shifted

你应该能够创建一个为你做这个的课程。如果有更多相同的话,它可以从任意大小的值中移出任意数量。

答案 2 :(得分:2)

bitstring模块可能有所帮助(文档here)。此示例创建一个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

答案 3 :(得分:1)

如果你想要一个数字的低32位,你可以使用二进制 - 如下所示:

 >>> low32 = (1 << 32) - 1
 >>> n = 0x12345678
 >>> m = ((n << 20) | (n >> 12)) & low32
 >>> "0x%x" % m
 '0x67812345'