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
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 = [11111011001101011001101011001100, 11111111000011001101001100111111,
11000000111100001111000011110000, 11111111000000001111011100001111]
num = myList[0]
example = num << 4
print("original", num)
print("shifted", 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 python-3.x , int
s 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)
print("original", bin(num))
print("shifted", bin(example))
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.