jim*_*ner 2 java boolean bit-manipulation operator-keyword
最近我在一本书中遇到了一个代码片段,它Boolean为这样的字段设置了一个值
输入identifier是一个List的String小号
if (identifier.size() >= 2) {
int c = Integer.parseInt(identifier.get(1));
bulk = (c & 4) == 4;
hazardous = (c & 2) == 2;
toxic = (c & 1) == 1;
}
Run Code Online (Sandbox Code Playgroud)
这里对一元和操作者的需求是什么?不能用简单的
c==4等代替(c & 4)== 4吗?
不,这是一个按位操作.
想象一下c=7.在这种情况下,所有条件都是正确的.
c = 7;
bulk = (c & 4) == 4; // true
hazardous = (c & 2) == 2; //true
toxic = (c & 1) == 1; //true
Run Code Online (Sandbox Code Playgroud)
在二进制文件中,你有这个:
c = 0111; //4-bit to simplify output
bulk = (c & 0100) == 0100; //
hazardous = (c & 0010) == 0010; //true
toxic = (c & 0001) == 0001; //true
Run Code Online (Sandbox Code Playgroud)
由于按位AND(&)你得到0111 & 0010 = 0010等.
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |