Javascript simple binary

Date: 2020-01-29
const binary = (dec) => (dec >>> 0).toString(2).padStart(8, '0');
const output = (...a) => Array.from(...a).forEach(x => console.log(binary(x), x));
output([
	20,
	19,
	20 ^ 19
]);
00010100 20
00010011 19
00000111 7

https://stackoverflow.com/a/1436448

To get a bit mask:

var mask = 1 << 5; // gets the 6th bit

To test if a bit is set:

if ((n & mask) != 0) {
  // bit is set
} else {
  // bit is not set
}

To set a bit:

n |= mask;

To clear a bit:

n &= ~mask;

To toggle a bit:

n ^= mask;
33040cookie-checkJavascript simple binary