How can I limit the number of bits in an integer variable in Python?

I want to implement the IDEA algorithm in Python. In Python, we have no limit on the size of the variable, but I need to limit the number of bits in an integer, for example, to rotate left. What do you advise?

+4
source share
4 answers

One way is to use the BitVector library.

Usage example:

>>> 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 
+3
source

8-bit mask with cyclic left shift:

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

You should be able to create a class that does this for you. With a little more than that, it can shift an arbitrary amount from an arbitrary size.

+2
source

The bitstring module can help (documentation here ). This example creates a 22-bit bit string and rotates 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 
+2
source

If you want to get 32 ​​bits of a number, you can use binary code and so:

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

All Articles