我注意到我可以用2 << 5来得到64,用1000 >> 2来得到250。
我也可以在打印中使用>>:
print >>obj, "Hello world"
这里发生了什么?
我注意到我可以用2 << 5来得到64,用1000 >> 2来得到250。
我也可以在打印中使用>>:
print >>obj, "Hello world"
这里发生了什么?
当前回答
它们是存在于许多主流编程语言中的位移位运算符,<<是左移,>>是右移,它们可以演示如下表,假设一个整数只占用内存1字节。
| operate | bit value | octal value | description |
| ------- | --------- | ----------- | -------------------------------------------------------- |
| | 00000100 | 4 | |
| 4 << 2 | 00010000 | 16 | move all bits to left 2 bits, filled with 0 at the right |
| 16 >> 2 | 00000100 | 4 | move all bits to right 2 bits, filled with 0 at the left |
其他回答
它们是存在于许多主流编程语言中的位移位运算符,<<是左移,>>是右移,它们可以演示如下表,假设一个整数只占用内存1字节。
| operate | bit value | octal value | description |
| ------- | --------- | ----------- | -------------------------------------------------------- |
| | 00000100 | 4 | |
| 4 << 2 | 00010000 | 16 | move all bits to left 2 bits, filled with 0 at the right |
| 16 >> 2 | 00000100 | 4 | move all bits to right 2 bits, filled with 0 at the left |
我在Python 2.7和Python 3.8上验证了以下内容
打印(100<<3) 将100转换为二进制得到1100100。 我所做的是去掉前3位,并在最后添加3位值为“0”的位。 所以结果应该是0100000,我把它转换成十进制,结果是32。
令我惊讶的是,当我执行print(100<<3)时,答案是800。我很困惑。 我把800转换成二进制来检查发生了什么。 这是1100100000。
如果你看到800是Python的答案,他们没有移位或删除前3位,而是将值“0”添加到最后3位。
其中作为打印(100>>3),工作完美。我做了手动计算,并从python中检查了打印结果。它工作正常。删除最后3位,并将值“0”添加到前3位。
看起来像(100<<3),左移运算符在Python上有一个错误。
这些是位移位运算符。
从文件中引用:
x << y
返回x,其中的位向左移动了y位(右边的新位为零)。这就等于x乘以2**y。
x >> y
返回x,位向右移动y位。这和x除以2**y是一样的。
2 << 5(左移)
向左移动2(二进制)5位。(向右注入0)
bin(16) # '0b10'
shifted = bin(2) + '0' * 5 # '0b1000000'
int(shifted, 2) # 64
2 << 5 # 64
1000 >> 2(右移)
向右移动1000(二进制)2位。(往左注入0)
bin(1000) # '0b1111101000'
# add 00 to the left and remove last digit from the right
# '0b 00(add these bits) 11111010 00(remove these bits)'
shifted = '0b0011111010'
int(shifted, 2) # 250
1000 >> 2 # 250
这些是移位运算符
x << y返回x,其中比特向左移动y位(和 右边的新位是零)。这和 x乘以2**y。 x >> y返回x,位移位到 右移y位。这和//'ing x * 2* y是一样的。