October 14, 1999 - The Bitwise AND Operator | WebReference

October 14, 1999 - The Bitwise AND Operator

Yehuda Shiran October 14, 1999
The Bitwise AND Operator
Tips: October 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

The bitwise AND operator compares two bits and assign 1 to the result only if both operands are 1. Here is the truth table for this operator:

Bit1Bit2Bit1 & Bit2
000
010
100
111

The AND operator, like all other bitwise operators, can take only numeric values as its operands. Since JavaScript does not support bit-length variables, you have to do your bitwise math with byte-length operands, i.e. with integers that are less than 256. Any operand longer than a byte (greater than 255) will be chopped and only the LSB (Least Significant Byte) will be used.

Let's do a simple calculation:

NameDecimalHexBinary
Op1350x2300100011
Op21140x7201110010
Op1 & Op2340x2200100010

You can use bitwise operands for many different tasks. The following function uses the bitwise AND operator to determine whether the number is odd or even. It returns a true value if decimalNumber is even, and a false value if it is odd:

function checkEven(decimalNumber) {
  return (decimalNumber & 1 == 0)
}