Languages
[Edit]
EN

JavaScript - bitwise operators

8 points
Created by:
Violetd
925

JavaScript like other languages provides bitwise operators.

Bitwise operators:

OperatorSymbolExample
NOT~
     00000101
NOT  --------
     11111010
// ONLINE-RUNNER:browser;

const a = 5;  // 00000101

const result = ~a;  // <-- bitwise NOT operation example

console.log(result);              // -6       (dec)
console.log(getBits(result, 8));  // 11111010 (bin)


function getBits(number, length) {
	let text = '';
  	for (let i = length - 1; i > -1; --i) {
    	text += 0x01 & (number >> i);
    }
  	return text;
}
AND&
     0011
     0101
AND  ----
     0001
// ONLINE-RUNNER:browser;

const a = 3;  // 0011
const b = 5;  // 0101

const result = a & b;  // <-- bitwise AND operation example

console.log(result);           // 1    (dec)
console.log(getBits(result));  // 0001 (bin)


function getBits(number) {
    return number.toString(2).padStart(4, '0');
}
OR|
     0011
     0101
 OR  ----
     0111
// ONLINE-RUNNER:browser;

const a = 3;  // 0011
const b = 5;  // 0101

const result = a | b;  // <-- bitwise OR operation example

console.log(result);           // 7    (dec)
console.log(getBits(result));  // 0111 (bin)


function getBits(number) {
	return number.toString(2).padStart(4, '0');
}
XOR^
      0011
      0101
 XOR  ----
      0110
// ONLINE-RUNNER:browser;

const a = 3;  // 0011
const b = 5;  // 0101

const result = a ^ b;  // <-- bitwise XOR operation example

console.log(result);           // 6    (dec)
console.log(getBits(result));  // 0110 (bin)


function getBits(number) {
	return number.toString(2).padStart(4, '0');
}

TODO: add other operators

See also

  1. JavaScript - bitwise NOT operator

  2. JavaScript - bitwise AND operator

  3. JavaScript - bitwise OR operator

  4. JavaScript - bitwise XOR operator

Alternative titles

  1. JavaScript - bit operators
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join