Bitwise Operators

Bitwise operators work with operands that are 32-bit integers. These are numbers written in binary (base two) that have 32 digits made up of just 0s and 1s. Here are some examples:


5 is written as 00000000000000000000000000000101
100 is written as 00000000000000000000000001100100
15 is written as 00000000000000000000000000001111
  

JavaScript will convert any values used with bitwise operators into a 32-bit integer and then carry out the operation.


Bitwise NOT

The bitwise NOT operator [~] will convert the number to a 32-bit integer, then change all the 1s to 0 and all the 0s to 1s. For example, 2476 can be represented as: 


000000000000000001011010101100  

Which will change to:

111111111111111110100101010011 

This is 1073736019, but the result actually uses negative values, as you can see in the code:


~44;
<< -45
  

In most cases, this operator will return an integer that adds to the original operand
to make -1.



Bitwise AND

You can also use the bitwise AND operator, [&], which will convert both numbers into binary and returns a number that in binary has a 1 in each position for which the corresponding bits of both operands are 1s. Here’s an example:

12 & 10; // in binary this is 1100 & 1010, so only the first digitis 1 in both cases
<< 8
  

It can also be used with non-integers, where it returns 1 for true and 0 for false.

5 & "hello"; // both are true
<< 1
  

Bitwise OR

There is also the bitwise OR operator, [|], which will convert both numbers into binary and return a number that in binary has a 1 in each position for which the corresponding bits of either operands are 1s. Here’s an example:

12 | 10; // in binary this is 1100 & 1010, so the first 3 digitscontain a 1
<< 14
  

This can also be used with non-integers, and returns 1 for true and 0 for false.


'' | "";
<< 0 // both are falsy
  


Bitwise XOR

Another operation is the bitwise XOR operator, [^], which stands for "eXclusive OR". This will convert both numbers into binary and return a number that in binary has a 1 in each position for which the corresponding bits of either operands are 1s, but not both 1s. Here’s an example:


12 ^ 10; // in binary this is 1100 & 1010, so only the second andthird digits are exclusively 1s
<< 6
  

When using non-integer values, this evaluates to 1 if either operands are truthy and evaluates to 0 if both operands are truthy or both are falsy:


1 ^ 0; // The first operand is truthy
<< 1

true ^ true; // if both operands are true then the result is false
<< 0
  



Bitwise Shift Operators

The bitwise shift operators, << and >>, will move the binary representation a given number of places to the right or left, which effectively multiplies or divides the number by powers of two:


3 << 1; // multiply by 2
<< 6

16 >> 1; // divide by 2
<< 8


5 << 3; multiply by 2 cubed (8)
<< 40
  


0 Response to "Bitwise Operators"

Post a Comment