HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Bitwise Operators

Bitwise operators work on 32-bit numbers. Any numeric operand in a bitwise operation is converted into a 32-bit binary number (a sequence of 0s and 1s) before the operation is performed. The result is then converted back to a standard JavaScript number.


Bitwise Operators Table

Here are the common bitwise operators in JavaScript:

Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits (0 becomes 1, 1 becomes 0)
<< Left Shift Shifts bits left by pushing zeros in from the right
>> Right Shift Shifts bits right (maintains sign bit)
>>> Zero-fill Right Shift Shifts bits right by pushing zeros in from the left

How Bitwise Works

Bitwise operations might seem confusing at first because we don't usually think in binary. Let's look at a simple example using Bitwise AND (&) with the numbers 5 and 1.

  • Binary for 5: 00000101
  • Binary for 1: 00000001
let result = 5 & 1; // Binary: 00000001 (Decimal: 1)
console.log(result); // 1

In this case, only the last bit is 1 in both numbers, so only that bit remains 1 in the result.


Common Use Cases

Bitwise operators are not used very often in daily web development, but they are extremely fast and useful in specific areas:

  • Working with Flags: Storing multiple true/false values in a single number.
  • Graphics and Games: Performing low-level pixel manipulations.
  • Cryptography: Encrypting and decrypting data.
  • Performance: Some bitwise operations (like shifting) are faster than standard multiplication or division by powers of 2.

The Bitwise NOT (~) Operator

The bitwise NOT operator inverts a number. Because JavaScript uses signed 32-bit integers, inverting a number x results in -(x + 1).

console.log(~5); // -6
console.log(~10); // -11
Note: Bitwise operators are rarely needed for beginner JavaScript projects, but understanding them helps you understand how computers process data at the lowest level.

Key Points to Remember

  • Bitwise operators treat numbers as 32-bit binary sequences
  • Operators like &, |, and ^ compare corresponding bits
  • Shift operators (<<, >>) move bits left or right
  • The result of a bitwise operation is always a signed 32-bit integer
  • They are faster than standard arithmetic but harder for humans to read