Pet*_*ter 111
超级(可能超过)简化定义仅<<
用于"时间2"并且>>
用于"除以2" - 其后的数字是多少次.
所以n << x
是"n次2次,x次".并且y >> z
是"y除以2,z次".
例如,1 << 5
是"1次2,5次"或32.并且32 >> 5
是"32除以2,5倍"或1.
所有其他答案都给出了更多的技术定义,但是没有人真正直截了当地说出来,我认为你可能会想要这样.
jco*_*ctx 88
根据http://golang.org/doc/go_spec.html中的规范,似乎至少对于整数,它是二进制移位.例如,二进制0b00001000 >> 1将为0b00000100,而0b00001000 << 1将为0b00010000.
Go显然不接受二进制整数的0b表示法.我只是用它作为例子.在十进制中,8 >> 1是4,而8 << 1是16.向左移动一次与乘以2相同,向右移一次与除以二相同,丢弃任何余数.
pet*_*rSO 29
<<和>>运算符是Go算术运算符.
<< left shift integer << unsigned integer
>> right shift integer >> unsigned integer
Run Code Online (Sandbox Code Playgroud)
移位运算符将左操作数移位右操作数指定的移位计数.如果左操作数是有符号整数,则它们实现算术移位;如果是无符号整数,则它们实现逻辑移位.移位计数必须是无符号整数.班次计数没有上限.对于移位计数n,移位的行为就好像左操作数被移位n次1.结果,x << 1与x*2相同,x >> 1与x/2相同,但截断为负无穷大.
小智 13
n << x = n * 2^x \xc2\xa0\xc2\xa0示例:3 << 5 = 3 * 2^5 = 96
\ny >> z = y / 2^z \xc2\xa0\xc2\xa0示例:512 >> 4 = 512 / 2^4 = 32
\n它们基本上是算术运算符,它在其他语言中是相同的,这是一个基本的PHP,C,Go示例
走
package main
import (
"fmt"
)
func main() {
var t , i uint
t , i = 1 , 1
for i = 1 ; i < 10 ; i++ {
fmt.Printf("%d << %d = %d \n", t , i , t<<i)
}
fmt.Println()
t = 512
for i = 1 ; i < 10 ; i++ {
fmt.Printf("%d >> %d = %d \n", t , i , t>>i)
}
}
Run Code Online (Sandbox Code Playgroud)
C
#include <stdio.h>
int main()
{
int t = 1 ;
int i = 1 ;
for(i = 1; i < 10; i++) {
printf("%d << %d = %d \n", t, i, t << i);
}
printf("\n");
t = 512;
for(i = 1; i < 10; i++) {
printf("%d >> %d = %d \n", t, i, t >> i);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
PHP
$t = $i = 1;
for($i = 1; $i < 10; $i++) {
printf("%d << %d = %d \n", $t, $i, $t << $i);
}
print PHP_EOL;
$t = 512;
for($i = 1; $i < 10; $i++) {
printf("%d >> %d = %d \n", $t, $i, $t >> $i);
}
Run Code Online (Sandbox Code Playgroud)
他们都会输出
1 << 1 = 2
1 << 2 = 4
1 << 3 = 8
1 << 4 = 16
1 << 5 = 32
1 << 6 = 64
1 << 7 = 128
1 << 8 = 256
1 << 9 = 512
512 >> 1 = 256
512 >> 2 = 128
512 >> 3 = 64
512 >> 4 = 32
512 >> 5 = 16
512 >> 6 = 8
512 >> 7 = 4
512 >> 8 = 2
512 >> 9 = 1
Run Code Online (Sandbox Code Playgroud)
小智 7
Go的<<和>>类似于其他语言中的移位(即:除法或乘以2的幂),但是因为Go是一种比C/C++更安全的语言,所以当移位计数是一个数字时,它会做一些额外的工作.
x86 CPU中的移位指令仅考虑移位计数的5位(64位x86 CPU上的6位).在C/C++等语言中,移位运算符转换为单个CPU指令.
以下Go代码
x := 10
y := uint(1025) // A big shift count
println(x >> y)
println(x << y)
Run Code Online (Sandbox Code Playgroud)
版画
0
0
Run Code Online (Sandbox Code Playgroud)
而C/C++程序会打印出来
5
20
Run Code Online (Sandbox Code Playgroud)
<<
是左移. >>
当左操作数是有符号整数时,是符号扩展右移,当左操作数是无符号整数时,是右移右移.
为了更好地理解>>
想到的
var u uint32 = 0x80000000;
var i int32 = -2;
u >> 1; // Is 0x40000000 similar to >>> in Java
i >> 1; // Is -1 similar to >> in Java
Run Code Online (Sandbox Code Playgroud)
因此,当应用于无符号整数时,左边的位用零填充,而当应用于有符号整数时,左边的位用最左边的位填充(当有符号整数为负2时为1)补充).