I was reading through some code examples and came across a &
on Oracle's website on their Bitwise and Bit Shift Operators page. In my opinion it didn't do too well of a job explaining the bitwise &
. I understand that it does a operation directly to the bit, but I am just not sure what kind of operation, and I am wondering what that operation is. Here is a sample program I got off of Oracle's website: http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/java/nutsandbolts/examples/BitDemo.java
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
.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With