+ 1
Whats the point
So i came across this problem and it has this line that went like this: system.out.println( ((n & 1) ==1 || (6 <= n && n <=20)) ? "Weird" : "Not Weird"); the question was to see if a number was even or not and answer it as weird or not weird so my question is what does that (&) do also what can (&) be applied to as well because from what i have learned about it i can't figure out any uses for it
1 Réponse
+ 2
This is a bitwise AND (&) it works on the binary (or base 2) of the lvalue and rvalue.
So let's say that the variable n had the value of 3, so we have 3 & 1
3 in binary is 0011
1 in binary is 0001
Now we AND their bits;
When using bitwise AND: 1 and 1 = 1, 0 and 1 = 0, 1 and 0 = 0, 0 and 0 = 0
In other words both bits in that place must be 1 in order to get 1 otherwise 0.
0011
0001
_____
0001 = 1
Bitwise OR works similarly, but if either bits are 1 then we get 1. We only get 0 if both bits are 0.
Binary (base 2) works right to left where the right most place is the ones place and the next place to the left of it is the twos place, then the fours place and so on. Place values are on if 1 and off if 0. They double for each shift to the left. So four bit place values are 8 4 2 1.
1 = 0001
2 = 0010
4 = 0100
8 = 1000
Place values are added together to get the actual base 10(decimal) number.
8421
1011 = 8 + 2 + 1 = 11
More info on bitwise operators:
https://www.tutorialspoint.com/java/java_basic_operators.htm