Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中如何限制整数变量的位数?_Python_Algorithm_Cryptography - Fatal编程技术网

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

在Python中如何限制整数变量的位数?,python,algorithm,cryptography,Python,Algorithm,Cryptography,我想用Python实现算法。在Python中,我们对变量大小没有限制,但我需要限制整数中的位数,例如,执行循环左移位。您有什么建议?一个循环左移的8位掩码: shifted = number << 1 overflowed = (number & 0x100) >> 8 shifted &= 0xFF result = overflowed | shifted shift=number>8 移位&=0xFF 结果=溢出|移位 您应该能够为自己创建一个这

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

一个循环左移的8位掩码:

shifted = number << 1
overflowed = (number & 0x100) >> 8
shifted &= 0xFF
result = overflowed | shifted
shift=number>8
移位&=0xFF
结果=溢出|移位

您应该能够为自己创建一个这样做的类。如果使用更大的相同值,它可以从任意大小的值中移出任意数量。

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

 >>> low32 = (1 << 32) - 1
 >>> n = 0x12345678
 >>> m = ((n << 20) | (n >> 12)) & low32
 >>> "0x%x" % m
 '0x67812345'
>>low32=(1>>n=0x12345678
>>>m=((n>12))&低32
>>>0x%x“%m”
“0x67812345”
一种方法是使用库

使用示例:

>>> 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
>>从位向量导入位向量
>>>bv=位向量(intVal=0x13A5,大小=32)
>>>打印bv
00000000000000000001001110100101
>>>bv>>打印bv
00000000000001001110100101000000
>>>bv[0]=1
>>>打印bv
10000000000001001110100101000000
>>>bv>>打印bv
00000000001001110100101000000100
该模块可能有帮助(文档)。此示例创建一个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

实现您自己的包装器类,该类施加了这些限制,因此