Wil*_*iam 15 java operators bit-shift
好吧,我尝试查找>>或者移动意味着什么,但是这个网站解释了它:http://www.janeg.ca/scjp/oper/shift.html
那么有人可以解释它就像他们正在和一个孩子说话吗?
In *_*ico 33
计算机是二进制设备.因此,数字由1和0的序列表示.
Bitshifting只是向左或向右移动1和0的序列.
所以>>操作员所做的就是将位向右移一位.
考虑数字101:
// Assuming signed 8-bit integers
01100101 // How 101 is represented in binary
00110010 // After right shifting one bit, this represents 50
Run Code Online (Sandbox Code Playgroud)
在这种情况下,最不重要的位被截断.显而易见的是细节中的魔鬼,但这就是真的.
在<<操作者不相反的操作:
// Assuming signed 8-bit integers
01100101 // How 101 is represented in binary
11001010 // After left shifting one bit, this represents -54
// Assuming unsigned 8-bit integers
01100101 // How 101 is represented in binary
11001010 // After left shifting one bit, this represents 202
Run Code Online (Sandbox Code Playgroud)
在这种情况下,最重要的位被截断,因为我只使用了8位.但是,如果数字有更多位,则:
// Assuming signed 16-bit integers
00000000 01100101 // How 101 is represented in binary
00000000 11001010 // After left shifting one bit, this represents 202
00000001 10010100 // After left shifting one bit again, this represents 404
Run Code Online (Sandbox Code Playgroud)
因此,您可能会得到不同的数字,具体取决于与您正在处理的那些位相关联的位数和数据类型.
附录:如果您想知道二进制是如何工作的,请考虑十进制数系统的工作原理.考虑数字5287.可以这样写:
5287
Run Code Online (Sandbox Code Playgroud)
但你也可以这样写出来:
5287 = (5 * 1000) + (2 * 100) + (8 * 10) + (7 * 1)
Run Code Online (Sandbox Code Playgroud)
你可以写出这样的:
5287 = (5 * 10^3) + (2 * 10^2) + (8 * 10^1) + (7 * 10^0)
Run Code Online (Sandbox Code Playgroud)
上面的等式解释了为什么十进制数系统有时被称为基数为10的系统.十进制数系统使用10位数(0-9).注意指数如何对应于数字位置.
二进制数系统或base-2系统完全相同,但是数字2作为指数的基数,并且只使用两个数字:0和1.
5287 = 00010100 10100111 (base 2)
= (0 * 2^15) + (0 * 2^14) + (0 * 2^13) + (1 * 2^12)
+ (0 * 2^11) + (1 * 2^10) + (0 * 2^9) + (0 * 2^8)
+ (1 * 2^7) + (0 * 2^6) + (1 * 2^5) + (0 * 2^4)
+ (0 * 2^3) + (1 * 2^2) + (1 * 2^1) + (1 * 2^0)
Run Code Online (Sandbox Code Playgroud)
我可以假设我正在与之交谈的孩子对二进制有所了解吗?:)
所有数字都可以用某种二进制表示,如下所示:
Base 10 : Base 2
1 : 0001
2 : 0010
3 : 0011
4 : 0100
5 : 0101
6 : 0110
7 : 0111
8 : 1000
Run Code Online (Sandbox Code Playgroud)
... 等等。
移位运算符基本上将所有位(1 或 0)移动到一个位置。所以,例如:000111 >> 1
将 000111 中的所有位右移一个数字以产生以下结果:
000011
000111<<1
将所有这些位左移一,以产生这个:
001110
如果您移位不止一个,那么它只会进一步移动这些位。
现在,根据您使用的语言和您使用的数字类型,它可能比这更复杂一点。例如,如果您使用一种语言,其中“最高有效位”(数字中最左边的一位)代表数字是否有符号,则该语言必须考虑到这一点。
从数学上讲,如果你取一个整数(并忽略溢出的风险,这是由计算机用完空间来存储位引起的),左移 1 (<< 1) 相当于乘以 2,然后移位右除以 1 相当于除以 2。(想想二进制数学中的“位值”是多少,这是有道理的)