Skip to main content

Bitwise Operators

Bitwise operators are used for manipulating data at the bit level. In other words, these operators allow you to examine and change the individual bits in an operand. In TypeScript, we have several bitwise operators, including Bitwise AND, Bitwise OR, Bitwise XOR, Bitwise NOT, Left Shift, and Right Shift. This article will explain each of these operators in detail, and provide examples of their use.

Bitwise AND (&)

The bitwise AND operator (&) returns a number representing the bits that are set in both the first operand and the second operand.

let a: number = 5;  // It is 0101 in binary
let b: number = 1; // It is 0001 in binary

console.log(a & b); // Output: 1

Bitwise OR (|)

The bitwise OR operator (|) returns a number representing the bits that are set in either the first operand or the second operand (or both).

let a: number = 5;  // It is 0101 in binary
let b: number = 3; // It is 0011 in binary

console.log(a | b); // Output: 7

Bitwise XOR (^)

The bitwise XOR (exclusive OR) operator (^) returns a number representing the bits that are set in exactly one of the two operands.

let a: number = 5;  // It is 0101 in binary
let b: number = 3; // It is 0011 in binary

console.log(a ^ b); // Output: 6

Bitwise NOT (~)

The bitwise NOT operator (~) inverts the bits of its operand.

let a: number = 5;  // It is 0101 in binary

console.log(~a); // Output: -6

Left Shift (<<)

The left shift operator (<<) moves all bits in its first operand to the left by the number of places specified in the second operand. Bits that are shifted off the end are discarded, and zeros are added at the other end.

let a: number = 5;  // It is 0101 in binary

console.log(a << 1); // Output: 10

Right Shift (>>)

The right shift operator (>>) moves all bits in its first operand to the right by the number of places specified in the second operand. Bits that are shifted off the end are discarded, and copies of the leftmost bit are added at the other end.

let a: number = 5;  // It is 0101 in binary

console.log(a >> 1); // Output: 2

Zero-Fill Right Shift (>>>)

The zero-fill right shift operator (>>>) behaves like the right shift operator, but fills in zeros at the left end.

let a: number = 5;  // It is 0101 in binary

console.log(a >>> 1); // Output: 2

These are the commonly used bitwise operators in TypeScript. They can be quite useful when you need to perform low-level data manipulation. However, they can also be a little tricky to understand if you're not familiar with binary numbers, so take some time to practice with them and get a feel for how they work.