Java Reference
In-Depth Information
Bitwise Operators
Bitwise operators work with operands that are 32-bit integers. These are numbers written in
binary (base two) that have 32 digits made up of just
0
s and
1
s. Here are some examples:
5 is written as 00000000000000000000000000000101
100 is written as 00000000000000000000000001100100
15 is written as 00000000000000000000000000001111
JavaScript will convert any values used with bitwise operators into a 32-bit integer and then
carry out the operation.
Bitwise NOT
The bitwise NOT operator [
~]
will convert the number to a 32-bit integer, then change all
the
1
s to
0
and all the
0
s to
1
s. For example, 2476 can be represented as:
000000000000000001011010101100
Which will change to:
111111111111111110100101010011
This is 1073736019, but the result actually uses negative values, as you can see in the code:
~44;
<< -45
In most cases, this operator will return an integer that adds to the original operand to make
-1.
