[英]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. 我试图在Python中声明一个32位二进制数(1和0)的列表,在列表中选择一个数字,然后移动。
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 现在我要从列表中选择一个数字,并将其向左移动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: 因此,一和零代表10的幂。您可以使用
0b
前缀来指定您正在写入二进制数,因此:
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. 您可以使用
bin(..)
为显示二进制符号的数字生成字符串。 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 . 请注意,在python-3.x中 ,
int
具有任意长度 。 So if you want to obtain a 32-bit number, you will have to mask with 0xffffffff
(that is 32 set bits, so 0b11111111111111111111111111111111
): 因此,如果要获取32位数字, 则必须使用
0xffffffff
屏蔽 (即32个设置位,因此为0b11111111111111111111111111111111
):
myList = [0b11111011001101011001101011001100, 0b11111111000011001101001100111111,
0b11000000111100001111000011110000, 0b11111111000000001111011100001111]
num = myList[0]
example = (num << 4)
&0xffffffff
print("original", bin(num))
print("shifted", bin(example))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.