2

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

Eric
  • 91
  • 2
  • 12
  • 2
    Use **0b**11100011... to declare binary numbers. Print with `bin(number)`. – MB-F Mar 13 '17 at 13:43
  • Incidentally, there is no such thing as a "binary number" type in Python. Or any other base, for that matter. `0b11111111` and `0xFF` and `255` are all exactly identical ordinary integers. – Kevin Mar 13 '17 at 13:45
  • 1
    Possible duplicate of [How do you express binary literals in Python?](http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python) – MB-F Mar 13 '17 at 13:46

1 Answers1

5

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))
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555