About Lesson
Bitwise Operator
Used for operations at the binary level (less common):
- & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left shift), >> (Right shift)
Example:
JavaScript
let a = 5; // In binary: 0101
let b = 3; // In binary: 0011
// & (AND) - Sets each bit to 1 if both bits are 1
let andResult = a & b; // 0101 & 0011 = 0001 (1 in decimal)
console.log("a & b = " + andResult); // Output: 1
// | (OR) - Sets each bit to 1 if at least one of the bits is 1
let orResult = a | b; // 0101 | 0011 = 0111 (7 in decimal)
console.log("a | b = " + orResult); // Output: 7
// ^ (XOR) - Sets each bit to 1 if only one of the bits is 1
let xorResult = a ^ b; // 0101 ^ 0011 = 0110 (6 in decimal)
console.log("a ^ b = " + xorResult); // Output: 6
// ~ (NOT) - Inverts all the bits (negation)
let notResult = ~a; // ~0101 = 1010 (In two's complement, this is -6 in decimal)
console.log("~a = " + notResult); // Output: -6
// << (Left shift) - Shifts bits to the left, adding zeros from the right
let leftShiftResult = a << 1; // 0101 << 1 = 1010 (10 in decimal)
console.log("a << 1 = " + leftShiftResult); // Output: 10
// >> (Right shift) - Shifts bits to the right, discarding bits shifted off
let rightShiftResult = a >> 1; // 0101 >> 1 = 0010 (2 in decimal)
console.log("a >> 1 = " + rightShiftResult); // Output: 2