Typescript bitwise operators
Created By: chatGPT
Bitwise operators in TypeScript are used to perform operations on the binary representations of integers. This can be particularly useful when you want to manipulate data at a lower level. Here’s a brief overview of the bitwise operators available in TypeScript:
AND (
&
): This operator takes two bits and performs a logical AND operation.let a = 5; // (0101 in binary)\nlet b = 3; // (0011 in binary)\nlet result = a & b; // result is 1 (0001 in binary)
OR (
|
): This operator takes two bits and performs a logical OR operation.let a = 5; // (0101 in binary)\nlet b = 3; // (0011 in binary)\nlet result = a | b; // result is 7 (0111 in binary)
XOR (
^
): This operator takes two bits and performs a logical exclusive OR operation.let a = 5; // (0101 in binary)\nlet b = 3; // (0011 in binary)\nlet result = a ^ b; // result is 6 (0110 in binary)
NOT (
~
): This operator inverts the bits of its operand.let a = 5; // (0101 in binary)\nlet result = ~a; // result is -6 (inverts all bits)
Left Shift (
<<
): Shifts bits to the left by a specified number of positions, filling in with zeroes.let a = 5; // (0101 in binary)\nlet result = a << 1; // result is 10 (1010 in binary)
Right Shift (
>>
): Shifts bits to the right by a specified number of positions, preserving the sign bit.let a = 5; // (0101 in binary)\nlet result = a >> 1; // result is 2 (0010 in binary)
Unsigned Right Shift (
>>>
): Shifts bits to the right by a specified number of positions, filling in with zeroes regardless of the sign.let a = -5; // (1111...1011 in binary)\nlet result = a >>> 1; // result is 2147483645
You can apply these operators on numeric values. Below is an example demonstrating how you can combine these operators for a more practical application:
Understanding these bitwise operations can help optimize certain tasks, especially when dealing with flags or when you require efficient data processing.let permissions = 0; // 0000\npermissions |= 1; // Add read permission (0001)\npermissions |= 2; // Add write permission (0010)\npermissions &= ~2; // Remove write permission (0001)\nconsole.log(permissions); // Output: 1