TypeScript Bitwise Operators
Bitwise operators in TypeScript work on bits and perform bit-by-bit operations. They are mostly used when working with binary data or flags.
List of Bitwise Operators in TypeScript:
AND (&
)
The &
operator compares each bit of two numbers. It returns 1
only if both bits are 1
; otherwise, it returns 0
.
Example:
let a = 5; // 0101 in binary
let b = 3; // 0011 in binary
let result = a & b; // 0001 in binary, which is 1
console.log(result); // Output: 1
OR (|
)
The |
operator compares each bit of two numbers. It returns 1
if at least one of the bits is 1
.
Example:
let a = 5; // 0101 in binary
let b = 3; // 0011 in binary
let result = a | b; // 0111 in binary, which is 7
console.log(result); // Output: 7
XOR (^
)
The ^
operator compares each bit of two numbers. It returns 1
if the bits are different (one is 1
and the other is 0
).
Example:
let a = 5; // 0101 in binary
let b = 3; // 0011 in binary
let result = a ^ b; // 0110 in binary, which is 6
console.log(result); // Output: 6
NOT (~
)
The ~
operator inverts each bit of the operand (changes 1
to 0
and 0
to 1
).
Example:
let a = 5; // 0101 in binary
let result = ~a; // 1010 in binary, which is -6
console.log(result); // Output: -6
Left Shift (<<
)
The <<
operator shifts the bits of a number to the left by a specified number of positions. It adds 0
in the new positions on the right.
Example:
let a = 5; // 0101 in binary
let result = a << 1; // 1010 in binary, which is 10
console.log(result); // Output: 10
Right Shift (>>
)
The >>
operator shifts the bits of a number to the right by a specified number of positions.
Example:
let a = 5; // 0101 in binary
let result = a >> 1; // 0010 in binary, which is 2
console.log(result); // Output: 2
Unsigned Right Shift (>>>
)
The >>>
operator shifts the bits of a number to the right by a specified number of positions, but it always fills the new positions with 0
regardless of the sign of the number.
Example:
let a = -5; // 11111111111111111111111111111011 in binary
let result = a >>> 1; // 01111111111111111111111111111101 in binary, which is 2147483643
console.log(result); // Output: 2147483643
Conclusion
Bitwise operators are helpful when dealing with low-level operations such as flags or binary data. The operators work at the bit level and can be used to manipulate data efficiently.