Javascript Bitwise Operations

JS Code Snippets Bitwise Operators
Share:

About

In this code snippet, we’ll learn how to use the bitwise operators in Javascript.

Bitwise operators allow us to work and manipulate the actual bits and perform bitwise operations like AND, OR, XOR, NOT, ...

Let’s see the code example below.

Code:

//Bin to dec and vice versa conversions.///////////////

console.log(decToBin(15));
console.log(binToDec("1111"));

function decToBin(value){
  return (value >>> 0).toString(2);
}

function binToDec(value){
  return parseInt(value, 2).toString(10);
}

///////////////////////////////////////////////////////


//Bitwise operators.//////////////////////////////////

let number = 10; //1010 in binary

//Show original value in binary.
console.log("Bin: " + decToBin(number));

//Shift 1 bit right by adding a 0 to the front(left). Last bit gets removed: 1010 => 0101
number = number >>> 1; //If >> is used it will push copies of the leftmost bit to the right. 
console.log("Bin: " + decToBin(number) + " Dec: " + number);

//Shift 1 bit left. A 0 gets added as the last bit: 101 => 1010
number = number << 1;
console.log("Bin: " + decToBin(number) + " Dec: " + number);


//AND: 0011 & 0101 => 0001
number = 3 & 5;
console.log("AND Bin: " + decToBin(number) + " Dec: " + number);

//OR 1010 | 1101 => 1111
number = 10 | 13;
console.log("OR Bin: " + decToBin(number) + " Dec: " + number);

//XOR 0001 0100 ^ 0000 1111 => 0001 1011
number = 20 ^ 15;
console.log("XOR Bin: " + decToBin(number) + " Dec: " + number);

//NOT 1010 => 11111111111111111111111111110101 =>10101
//All the zeros that were ommited before will now turn into 1.
//Also the sign bit will now be a 1 thus making the number negative.
number = ~ 10;
console.log("NOT Bin: " + decToBin(number) + " Dec: " + number);

///////////////////////////////////////////////////////

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger