Oli*_*ack 1 java bit-manipulation
我试图理解这段代码,方法addBittoTree需要一个布尔值来传递.我不太清楚它在检查什么.我不明白为什么currentByte和-128有&符号,它是否使用它作为加法运算符?
byte currentByte = dis.readByte();
tree.addBitToTree( (currentByte & -128) == -128 );
Run Code Online (Sandbox Code Playgroud)
-128 in two's complemenet是
1000 0000
假设你的currentByte设置了第一位:
1000 0000 // -128
& // bitwise logical and
1010 1010 // currentByte (example)
is
1000 0000 // -128
Run Code Online (Sandbox Code Playgroud)
这是比较(==)-128,所以你传递boolean参数true.
另一个未设置第一位的示例:
1000 0000 // -128
& // bitwise logical and
0011 1110 // currentByte (example)
is
0000 0000 // 0
Run Code Online (Sandbox Code Playgroud)
这是比较(==)-128,所以你传递boolean参数false.
由于这种方式总是传递true给方法,当第一位被设置false时,当它没有被设置时,我们知道所有正数都没有第一位设置而所有负数都没有,所以相当于简单地写:
tree.addBitToTree(currentByte < 0);
Run Code Online (Sandbox Code Playgroud)