How Does The Bitwise & (AND) Work In Java?
It's a binary AND operator. It performs an AND operation that is a part of Boolean Logic which is commonly used on binary numbers in computing.
For example:
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
You can also perform this on multiple-bit numbers:
01 & 00 = 00
11 & 00 = 00
11 & 01 = 01
1111 & 0101 = 0101
11111111 & 01101101 = 01101101
...
If you expand the two variables according to their hex code, these are:
bitmask : 0000 0000 0000 1111
val: 0010 0010 0010 0010
Now, a simple bitwise AND operation results in the number 0000 0000 0000 0010
, which in decimal units is 2. I'm assuming you know about the fundamental Boolean operations and number systems, though.
If you look at two numbers represented in binary, a bitwise &
creates a third number that has a 1 in each place that both numbers have a 1. (Everywhere else there are zeros).
Example:0b10011011 &
0b10100010 =
0b10000010
Note that ones only appear in a place when both arguments have a one in that place.
Bitwise ands are useful when each bit of a number stores a specific piece of information.
You can also use them to delete/extract certain sections of numbers by using masks.
An integer is represented as a sequence of bits in memory. For interaction with humans, the computer has to display it as decimal digits, but all the calculations are carried out as binary. 123
in decimal is stored as 1111011
in memory.
The &
operator is a bitwise "And". The result is the bits that are turned on in both numbers. 1001 & 1100 = 1000
, since only the first bit is turned on in both.
The |
operator is a bitwise "Or". The result is the bits that are turned on in either of the numbers. 1001 | 1100 = 1101
, since only the second bit from the right is zero in both.
There are also the ^
and ~
operators, that are bitwise "Xor" and bitwise "Not", respectively. Finally there are the <<
, >>
and >>>
shift operators.
Under the hood, 123
is stored as either 01111011 00000000 00000000 00000000
or 00000000 00000000 00000000 01111011
depending on the system. Using the bitwise operators, which representation is used does not matter, since both representations are treated as the logical number 00000000000000000000000001111011
. Stripping away leading zeros leaves 1111011
.