JavaScript » Bitwise

Bitwise operators perform logical and shift operations. They work by treating their operands as a series of 32 bits and performing their operations on them at this bit level. However, the return value is a decimal format number.
The following examples of bitwise logical operators assume the variable 'a' to be 13 (binary 1101) and 'b' to be 9 (binary 1001)

& Operator


This is the bitwise AND operator which returns a 1 for each bit position where the corresponding bits of both its operands are 1. The following code would return 9 (1001):.

Examples

Code:
result = a & b;

| Operator


This is the bitwise OR operator and returns a one for each bit position where one or both of the corresponding bits of its operands is a one. This example would return 13 (1101).

Examples

Code:
result = a | b;

^ Operator

This is the bitwise XOR operator, which returns a one for each position where one (not both) of the corresponding bits of its operands is a one. The next example returns 4 (0100)

Code:
result = a ^ b;

~ Operator


This is the bitwise NOT operator and it works by converting each bit of its operand to its opposite. This example returns -14.

Examples

Code:
result = ~a;

<< Operator


This is the left shift operator and it works by shifting the digits of the binary representation of the first operand to the left by the number of places specified by the second operand. The spaces created to the right are filled in by zeros, and any digits falling off the left are discarded.

Examples

Code:
result = a << b;
Explanation:

The above code returns 52 as the binary of 13 (1101) is shifted two places to the left giving 110100:.

>> Operator


This is the sign-propagating right shift operator which shifts the digits of the binary representation of the first operand to the right by the number of places specified by the second operand, discarding any shifted off to the right. The copies of the leftmost bit are added on from the left, thereby preserving the sign of the number.This next example returns 3 (11) as the two right-most bit of 13 (1101) are shifted off to the right and discarded.

Examples

Code:
result = a >> b;
Explanation:

Note that if 'a' were -13 in the above example, the code would return -4 as the sign is preserved.

>>> Operator


This is the zero-fill right shift operator which shifts the binary representation of the first operand to the right by the number of places specified by the second operand. Bits shifted off to the right are discarded and zeroes are added on to the left.

Examples

Code:
result = a >>> b;
Explanation:

With a positive number you would get the same result as with the sign-propagating right shift operator, but negative numbers lose their sign becoming positive as in the above example, which (assuming 'a' to be -13) would return 1073741820.