繁体   English   中英

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

[英]How Can I limit bit number in the integer variable in Python?

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

一种方法是使用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

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM