JS Bitwise Operations

JS Bitwise Operations

JS Bitwise Operations

In JavaScript, bitwise operations are operations that are performed on the binary representation of a number. There are several bitwise operators in JavaScript:

  1. Bitwise AND (&): Returns a 1 in each bit position where both operands have a 1.
				
					let a = 5; // binary 101
let b = 3; // binary 011
let result = a & b; // binary 001 (decimal 1)

				
			
  1. Bitwise OR (|): Returns a 1 in each bit position where either or both operands have a 1.
				
					let a = 5; // binary 101
let b = 3; // binary 011
let result = a | b; // binary 111 (decimal 7)

				
			
  1. Bitwise XOR (^): Returns a 1 in each bit position where only one of the operands has a 1.
				
					let a = 5; // binary 101
let b = 3; // binary 011
let result = a ^ b; // binary 110 (decimal 6)

				
			
  1. Bitwise NOT (~): Inverts the bits of its operand, changing 1s to 0s and 0s to 1s. This operation is performed on the binary representation of the number, and the result is returned as a 32-bit signed integer.
				
					let a = 5; // binary 00000000000000000000000000000101
let result = ~a; // binary 11111111111111111111111111111010 (decimal -6)

				
			
  1. Left shift (<<): Shifts the bits of its first operand to the left by the number of places specified by the second operand. Zeros are shifted in from the right.
				
					let a = 5; // binary 101
let result = a << 2; // binary 10100 (decimal 20)

				
			
  1. Sign-propagating right shift (>>): Shifts the bits of its first operand to the right by the number of places specified by the second operand. Copies the sign bit from the leftmost bit to the right.
				
					let a = -5; // binary 11111111111111111111111111111011 (decimal -5)
let result = a >> 2; // binary 11111111111111111111111111111110 (decimal -2)

				
			
  1. Zero-fill right shift (>>>): Shifts the bits of its first operand to the right by the number of places specified by the second operand. Zeros are shifted in from the left.
				
					let a = -5; // binary 11111111111111111111111111111011 (decimal -5)
let result = a >>> 2; // binary 00111111111111111111111111111110 (decimal 1073741822)

				
			

It’s important to note that bitwise operations in JavaScript are performed on 32-bit integers, so any operands with more than 32 bits will have their extra bits truncated. Additionally, bitwise operations may not be very common in JavaScript programming, but they can be useful in certain situations, such as when working with binary data or performing low-level optimizations.

Join To Get Our Newsletter
Spread the love