Eric
Eric

Reputation: 91

How to declare a list of 32 bit binary numbers and shift in Python?

I am trying to declare a list of 32-bit binary numbers (1's and 0's) in Python, pick out a number in the list, and shift.

This is how I have my list declared, but I do not feel like this is correct.

myList = [11111011001101011001101011001100, 11111111000011001101001100111111,
     11000000111100001111000011110000, 11111111000000001111011100001111]

Now I want to select a number from my list and shift it to the left by 4

Example:

num = myList[0]
example = num << 4
print("original", num)
print("shifted", example)

The output looks like this:

original 11111011001101011001101011001100
shifted 177776176017616176017616176017600

How can I fix my declaration and shifting issues? Thanks

Upvotes: 2

Views: 2110

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477180

The problem is that:

11111011001101011001101011001100

is interpreted as a decimal number. So the ones and the zeros represent powers of 10. You can use the 0b prefix to specify you are writing binary numbers, so:

myList = [0b11111011001101011001101011001100, 0b11111111000011001101001100111111,
          0b11000000111100001111000011110000, 0b11111111000000001111011100001111]
num = myList[0]
example = num << 4
print("original", bin(num))
print("shifted", bin(example))

You can use bin(..) to generate a string for a number that shows the binary notation. This will print:

>>> print("original", bin(num))
original 0b11111011001101011001101011001100
>>> print("shifted", bin(example))
shifted 0b111110110011010110011010110011000000

Note that in , ints have arbitrary length. So if you want to obtain a 32-bit number, you will have to mask with 0xffffffff (that is 32 set bits, so 0b11111111111111111111111111111111):

myList = [0b11111011001101011001101011001100, 0b11111111000011001101001100111111,
          0b11000000111100001111000011110000, 0b11111111000000001111011100001111]
num = myList[0]
example = (num << 4)&0xffffffff
print("original", bin(num))
print("shifted", bin(example))

Upvotes: 5

Related Questions