Go << and>> operators

2019-01-30 03:27发布

Could someone please explain to me the usage of << and >> in Go? I guess it is similar to some other languages.

7条回答
在下西门庆
2楼-- · 2019-01-30 04:26

<< is left shift. >> is sign-extending right shift when the left operand is a signed integer, and is zero-extending right shift when the left operand is an unsigned integer.

To better understand >> think of

var u uint32 = 0x80000000;
var i int32 = -2;

u >> 1;  // Is 0x40000000 similar to >>> in Java
i >> 1;  // Is -1 similar to >> in Java

So when applied to an unsigned integer, the bits at the left are filled with zero, whereas when applied to a signed integer, the bits at the left are filled with the leftmost bit (which is 1 when the signed integer is negative as per 2's complement).

查看更多
登录 后发表回答