Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

JavaScript Bitwise Operators

Notes:

JavaScript Bitwise Operators:

Bitwise Operators: are used to perform operations on bits.
Bitwise operators convert the given decimal number(s) to their binary equivalent number,
and then they perform the operations on bits of those binary equivalent number(s).

&: Bitwise And operator:
If both LHS and RHS are 1 then the result will be 1, in all other cases result will be 0

|: Bitwise Or operator:
If both LHS and RHS are 0 then the result will be 0, in all other cases result will be 1

^: Bitwise Exclusive Or operator:
If both LHS and RHS are same then the result will be 0, otherwise the result will be 1

~: Bitwise complement operator:
To the given operand add 1 and change the sign

<<: Bitwise Left Shift operator:
Shifts the bits of first number to the left by number of positions indicated by second number
firstNumber * pow(2,secondNumber)

>>: Bitwise Right Shift operator:
Shifts the bits of first number to the right by number of positions indicates by second number
firstNumber / pow(2,secondNumber)

document.write("Bitwise Operators");
document.write(1 & 1); // 1
document.write(0 | 0); // 0
document.write(1 ^ 0); // 1
document.write(2 & 5); // 0
document.write(2 | 5); // 7
document.write(2 ^ 2); // 0
document.write(~5); // 5 + 1 = +6 change sign = -6
document.write(~(-3)); // -3+1 = -2 change sign = +2
document.write(1<<4); // 16
document.write(64>>2); // 16

Interview Questions:

1. 1<<4 the result is ________
a. 4
b. 16
c. 8
d. 32
Answer: b