Notation for logic in Java

对着背影说爱祢 提交于 2019-12-23 08:23:30

问题


Absolutely basic Java question which I'm having a hard time finding on Google. What does the following mean:

(7 & 8) == 0?

Is that equivalent to writing:

7 == 0 || 8 == 0?

I wrote a quick main which tests this, and it seems to be the case. I just wanted to make sure I'm not missing anything.


回答1:


Nope. & is bitwise and. It sets a bit if the corresponding bits are set in both inputs. Since in binary, 7 is 111 and 8 is 1000, they have no bits in common, so the result is 0.

There isn't really any shorthand syntax for the thing you suggest, not on a single line. There are a few workarounds -- test for membership in a Set or BitSet, use a switch statement -- but nothing that's both as efficient and as short as just 7 == 0 || 8 == 0.




回答2:


& is bitwise AND. Given two bits for inputs, the following gives the bit output by bitwise AND:

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

In this case,

7 in binary is 00000111
8 in binary is 00001000
               --------
               00000000, which is 0 in decimal.

Say you had 26 instead of 8.

 7 in binary is 00000111
26 in binary is 00011010
                --------
                00000010, which is 2 in decimal.

Bitwise operations are used to extract and manipulate fields packed into a number.

For example, let's say you had a 3 fields packed into one number, two of 4 bits each (0..15), one and 3 bits (0..7).

// n = aaaabbbbccc

// Unpack the fields:
a = (n >> 7) & 0xF;
b = (n >> 3) & 0xF;
c = (n >> 0) & 0x7;

// Pack the fields:
n = (a << 7)
  | (b << 3)
  | (c << 0);



回答3:


The & is a bit-wise AND operator. This means that you are ANDing the bits that represent 8 and 7:

7 -> 0111

8 -> 1000

Which obviously results in 0.

This wikipedia article explains it well with your exact example along with explaining the other bit-wise operators.




回答4:


It is bit comparison, working fine because you are comparing with 7 and 8, not guaranteed with other cases. If both bits in the integers matches you will get results as '1' not '0'.




回答5:


& is a bit comparison, as mentioned, but can also serve as a short-circuiting "and." For instance:

if((x == 3) &&  (y = 3/0)){

will throw an error all the time. However,

if((x == 3) & (y = 3/0)){

will only throw an error if x equals 3. If x does not equal 3, java will not bother evaluating the rest of the expressions because False & anything will be False.



来源:https://stackoverflow.com/questions/9203014/notation-for-logic-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!