Javascript Bitwise

Like other languages, JavaScript also supports bit-wise operations. In JavaScript, a number is stored as a 64-bit floating-point number but the bit-wise operation is performed on a 32-bit binary number i.e. to perform a bit-operation JavaScript converts the number into a 32-bit binary number (signed) and perform the operation and convert back the result to a 64-bit number.

Following are the bitwise logical operator used in Javascript:-


Bitwise AND(&)

This bitwise operator is a binary operator i.e. accepts two operands. Bit-wise AND (&) returns 1 if both the bits are set ( i.e 1) and 0 in any other case.

ABOutput(A & B)
000
010
100
111

Following is the example to illustrate the use of AND operator:-

Input:-
 <script>  
	   let result;
	   result = 4 & 1;
    document.write("4 & 1 is " + result + "<br>")
</script>

Output:-


Bitwise OR(|)

This bitwise operator is a binary operator i.e. accepts two operands. Bit-wise OR ( | ) returns 1 if any of the operand is set (i.e. 1) and 0 in any other case.

ABOutput(A | B)
000
011
101
111

                 Following is the example to illustrate the use of OR operator:-

Input:-
 <script>  
	   let result;
	   result = 4 | 1;
    document.write("4 | 1 is " + result + "<br>")
</script>

Output:-


Bitwise XOR(^)

This bitwise operator is a binary operator i.e. accepts two operands. Bit-wise XOR ( ^ ) returns 1 if both the operands are different and 0 in any other case.

ABOutput(A ^ B)
000
011
101
110

                 Following is the example to illustrate the use of XOR operator:-

Input:-
 <script>  
	   let result;
	   result = 4 ^ 1;
    document.write("4 ^ 1 is " + result + "<br>")
</script>

Output:-


Bitwise NOT(~)

This bitwise operator is a unary operator i.e. accepts single operands. Bit-wise NOT ( ~ ) flips the bits i.e 0 becomes 1 and 1 becomes 0.

AOutput(~A)
01
10

     Following is the example to illustrate the use of NOT operator:-

Input:-
 <script>  
	   let result;
	   result = ~4;
    document.write("~4 is " + result + "<br>")
</script>

Output:-