对于<<
, >>
两种运算符,可以这样说:
$a<
$a>>b=a/2^b$
但是对于>>>
…不好说了。
这些位运算在计算机中怎样运算的?
大家都知道,整数在计算机中是以二进制存储的:
$0 = (0)_2$
$4 = (100)_2$
$8 = (1000)_2$
$20 = (10100)_2$
$666 = (1010011010)_2$
左移(<<
)
$a << b$就是在$a$的二进制后面添上$b$个$0$,所以$a<
拿$20$当例子,
$20 << 1 = (10100)_2 << 1 = (101000)_2 = 40$,
$20 << 2 = (10100)_2 << 2 = (1010000)_2 = 80$。
右移(>>
)
>>
跟<<
相反,$a>>b$就是在$a$的二进制后面去掉$b$位,所以$a>>b=a/2^b$
还是拿$20$当例子:
$20 >> 1 = (10100)_2 >> 1 = (1010)_2 = 10$,
$20 >> 2 = (10100)_2 >> 2 = (101)_2 = 5$
如果末尾不是$0$呢?照样去:
$21 >> 1 = (10101)_2 >> 1 = (1010)_2 = 10$