Bitwise Operators
Bitwise operations are a bit of a hack in Javascript. Since all numbers in Javascript are floating point, and bitwise operators only work on integers, Javascript does a little behind the scenes magic to make it appear bitwise operations are being applied to a 32bit signed integer.
Specifically, Javascript takes the number you are working on and takes the integer portion of the number. It then converts the integer to the most number of bits that number represents, up to 31 bits (1 bit for the sign). So 0 would create a two bit number (1 for the sign, and 1 bit for 0), likewise 1 would create two bits. 2 would create a 3 bit number, 4 would create a 4 bit number, etc…
It's important to realize that you're not guaranteed a 32bit number, for instance running not on zero should, in theory, convert 0 to 4,294,967,295, instead it will return -1 for two reasons, the first being that all numbers are signed in Javascript so "not" always reverses the sign, and second Javascript couldn't make more than one bit from the number zero and not zero becomes one. Therefore ~0=-1.
So bitwise signs in Javascript are up to 32 bits.
Operator Description Notes
& AND 1&1=1,1&0=0
| OR 1|0=1, 0|0=0
^ XOR 1^1=0, 1^0=1
~ NOT (Unary) ~1=0, ~0=-1
<< Shift Left 1<<2=4 -- shift 1, 2 bits left
>> Shift Right 4
>>2=1 -- shift 4, 2 bits right (*)
>>> Shift Right 4>
>>2=1 -- shift 4, 2 bits right (*)
(*) When shifting right, double greater-thans (>>) will fill the new bits to the far left as 1s if the number was negative and zero if the number was positive. tripple greater-thans (>>>) is the same as double greater-thans but the fill bit will always be zero so the sign of the original number is not preserved and the result is always positive.
With the exception of the bitwise NOT operator (~), all operators can be expressed as (operator)= when working with the same number as the variable.
x = x&5; // is the same as x &= 5;
x = x|5; // is the same as x |= 5;
x = x^5; // is the same as x ^= 5;
x = x<<5; // is the same as x <<= 5;
x = x
>>5; // is the same as x >>= 5;
x = x>
>>5; // is the same as x >>>= 5;
One of the most common mistakes in Javascript is to use a bitwise operator in the place of a logical operator. For instance comparing two variables is expressed with the logical operator (&&), using a single & instead of a double && can yield unintended results. To avoid confusion you should always wrap bitwise operations in parenthesis to ensure it is not considered a logical evaluation!