Basic Bit Manipulations in JavaScript

·

Get Bit

We can use bitwise and operator to test if specific bit is 1 or 0.

``````function getBit(number, bitPosition) {
return (number >> bitPosition) & 1;
}

const x = 0b10101010;

for (let i = 0; i < 8; i++) {
const bit = getBit(x, i);
console.log(bit);
}
// 0
// 1
// 0
// 1
// 0
// 1
// 0
// 1
``````

Set Bit

We can use bitwise or operation to set specific position to 1 or 0.

``````function getBit(number, bitPosition) {
return (number >> bitPosition) & 1;
}

function setBit(number, bitPosition, bitValue) {
const clearMask = ~(1 << bitPosition);

// make bitPosition 0

// set bitValue
number = number | (bitValue << bitPosition);

return number;
}

let x = 0;

x = setBit(x, 5, 1);
console.log(getBit(x, 5)) // 1

x = setBit(x, 5, 0);
console.log(getBit(x, 5)) // 0
``````

isEven

Odd numbers have their last right bit to be set to 1.

``````function isEven(number) {
return (number & 1) === 0;
}

console.log(isEven(5)) // false
console.log(isEven(6)) // true
``````

Multiply By Two

Left shift equals to multiple by 2.

``````function multiplyByTwo(number) {
return number << 1;
}

console.log(multiplyByTwo(2)) // 4
``````

Divide By Two

Right shift equals to divide by 2.

``````function divideByTwo(number) {
return number >> 1;
}

console.log(divideByTwo(2)) // 1
``````