Bitwise Operators
Despite the fact that all numbers in JavaScript are floating-point, the bitwise operators require numeric operands that have integer values. They operate on these integer operands using a 32-bit integer representation instead of the equivalent floating-point representation. Four of these operators perform Boolean algebra on the individual bits of the operands, behaving as if each bit in each operand were a boolean value and performing similar operations to those performed by the logical operators we saw earlier. The other three bitwise operators are used to shift bits left and right.
In JavaScript 1.0 and JavaScript 1.1, the bitwise operators return
NaN
if used with operands that are not integers or
that are too large to fit in a 32-bit integer representation.
JavaScript 1.2 and ECMAScript, however, simply coerce the operands to
32-bit integers by dropping any fractional part of the operand or any
bits beyond the 32nd. The
shift
operators require a righthand operand between 0 and 31. After
converting this operand to a 32-bit integer as described earlier,
they drop any bits beyond the 5th, which yields a number in the
appropriate range.
If you are not familiar with binary numbers and the binary representation of decimal integers, you can skip the operators described in this section. The purpose of these operators is not described here; they are needed for low-level manipulation of binary numbers and are not commonly used in JavaScript programming. The bitwise ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.