简体   繁体   中英

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

I want to realize IDEA algorithm in Python. In Python we have no limits for variable size, but I need limit bit number in the integer number, for example, to do cyclic left shift. What do you advise?

One way is to use the BitVector library.

Example of use:

>>> 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

An 8-bit mask with a cyclic left shift:

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

You should be able to make a class that does this for you. With a bit more of the same, it can shift an arbitrary amount out of an arbitrary sized value.

The bitstring module might be of help (documentation here ). This example creates a 22 bit bitstring and rotates the bits 3 to the right:

>>> 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

If you want a the low 32 bits of a number, you can use binary-and like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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