不能使用 == 来代替一元 &检查两个值是否相等
最近,我在一本书中发现了一个代码片段,它将 Boolean
值设置为这样的字段,
输入 identifier
是 List
>Strings
if (identifier.size() >= 2) {
int c = Integer.parseInt(identifier.get(1));
bulk = (c & 4) == 4;
hazardous = (c & 2) == 2;
toxic = (c & 1) == 1;
}
需要什么一元&这里有运算符吗?这不能用一个简单的方法来完成吗 c==4
等而不是 (c & 4)== 4
?
Recently I came across a code snippet in a book which sets a Boolean
value to a field like this
the input identifier
is a List
of String
s
if (identifier.size() >= 2) {
int c = Integer.parseInt(identifier.get(1));
bulk = (c & 4) == 4;
hazardous = (c & 2) == 2;
toxic = (c & 1) == 1;
}
what is the need for unary & operators here?Can't this be done using a simplec==4
etc instead of (c & 4)== 4
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这是按位运算。
想象一下
c=7
。在这种情况下,所有条件都成立。在二进制中,你会得到这样的结果:
由于按位与(&),你会得到
0111 & 0010 = 0010
等No, this is a bitwise operation.
Imagine
c=7
. In that case all conditions would be true.In binary, you'd have this:
Due to bitwise AND (&) you get
0111 & 0010 = 0010
etc.这是为位掩码添加的
,如果
c = 3 那么它也会被认为是有毒的,
如果你这样写
,那么它将是 stcict 1 检查
This is added for bit masking
if
c =3 then also it will be considered as toxic with this
if you write
then it would be stcict 1 check
变量
c
显然是一个位掩码。执行按位&
的效果是屏蔽其他位,只留下一位仍然设置。例如,以下语句:测试
c
的位 2 是否已设置(并且不关心其他位) - 位 2 是该字节中的1
位:00000100
The variable
c
is clearly a bitmask. The effect of doing the bitwise&
is mask off the other bits, leaving just the one bit still set. For example, this statement:tests if bit 2 of
c
is set (and doesn't care about the other bits) - bit 2 being the1
bit in this byte:00000100
c == 4 检查 c 是否等于 4,这意味着 c 的二进制形式为 000...00100。 (c & 4) == 4 如果 c 的二进制形式如下 xxx...xx1xx。
c == 4 checks if c equals 4, meaning the binary form of c is 000...00100. (c & 4) == 4 if the binary form of c is the following xxx...xx1xx.