Bitwise operators perform operations on bit values of data. These operators convert operands to signed 32-bit integers in two's complement.
Conversion to 32-bit integers
Numbers with more than 32 bits discard their most significant bits. For example, the following integer with more than 32 bits is converted to a 32-bit integer:
In normal binary we find the binary value by adding the 1's based on their position as powers of 2 - The rightmost bit being 2^0 to the leftmost bit being 2^n-1 where n is the number of bits. For example, using 4 bits:
Two complement's format means that the number's negative counterpart (6 vs -6) is all the bits for a number inverted, plus one. The inverted bits of 6 would be:
Adding more 1's to the left of a binary number does not change its value in two's compliment. The value 1010
and 1111111111010 are both -6.
Bitwise shifting can be thought as "moving" the bits either left or right, and hence changing the value of the data operated on.
The left shift operator (value) << (shift amount) will shift the bits to the left by (shift amount) bits; the new bits coming in from the right will be 0's:
20: 0..010100 <= adds two 0's to the right
Right Shift (Sign-propagating)
The right shift operator (value) >> (shift amount) is also known as the "Sign-propagating right shift" because it keeps the sign of the initial operand. The right shift operator shifts the value the specified shift amount of bits to the right. Excess bits shifted off the right are discarded. The new bits coming in from the left will be based on the sign of the initial operand. If the left-most bit was 1 then the new bits will all be 1 and vice-versa for 0's.
//5: 0..000101 <= added two 0's from the left and chopped off 00 from the right
Right Shift (Zero fill)
The zero-fill right shift operator (value) >>> (shift amount) will move the bits to the right, and the new bits will be 0's. The 0's are shifted in from the left, and excess bits to the right are shifted off and discarded. This means it can make negative numbers into positive ones.
Zero-fill right shift and sign-propagating right shift yield the same result for non negative numbers.