为什么 `1<<32 - 1` 在 go 中是 4294967295?

Mil*_*son 1 c bit-shift go

我在 Go 中发现了一个奇怪的结果,你能帮我吗?

fmt.Print( 1<<32 - 1)

it's 4294967295
Run Code Online (Sandbox Code Playgroud)

但是在 C

 printf("%lld",0x1ll<<32 - 1);
it's 2147483648
Run Code Online (Sandbox Code Playgroud)

Pau*_*kin 18

在 go 中,1<<32-1解析为(1 << 32) - 1(gofmt 有用地暗示了它插入的空格)。在 C 中,它解析为1 << (32 - 1). 这是因为在 C 中,移位的优先级低于 + 和 -,而在 Go 中,则相反。

您可以在输出中看到这一点,在 go 中它是奇数,并且4294967295是 2^32 - 1。在 C 中它2147483648是 2^31。

Go 运算符优先级(来自https://golang.org/ref/spec#Operators

Precedence    Operator
    5             *  /  %  <<  >>  &  &^
    4             +  -  |  ^
    3             ==  !=  <  <=  >  >=
    2             &&
    1             ||
Run Code Online (Sandbox Code Playgroud)

在 C 中:https : //en.cppreference.com/w/c/language/operator_precedence