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

3
  • 2
    Use 0b11100011... to declare binary numbers. Print with bin(number). Commented Mar 13, 2017 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. Commented Mar 13, 2017 at 13:45
  • 1
    Possible duplicate of How do you express binary literals in Python? Commented Mar 13, 2017 at 13:46

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

3 Comments

leave some reputation for others to gain, you are always so fast:)
@GijsDenHollander: noted. Next time I will give you five minutes :)
@WillemVanOnsem Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.