October 14, 1999 - The Bitwise AND Operator
October 14, 1999 The Bitwise AND Operator Tips: October 1999
Yehuda Shiran, Ph.D.
|
Bit1 Bit2 Bit1 & Bit2 0 0 0 0 1 0 1 0 0 1 1 1
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:
Name Decimal Hex Binary Op1 35 0x23 0 0 1 0 0 0 1 1 Op2 114 0x72 0 1 1 1 0 0 1 0 Op1 & Op2 34 0x22 0 0 1 0 0 0 1 0
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)
}