Published
Edited
Nov 4, 2018
1 star
Insert cell
Insert cell
Insert cell
function isBitSet(n, k) {
return n & (1 << k) != 0;
}
Insert cell
isBitSet(5, 2)
Insert cell
Insert cell
function setBit(n, k) {
return n | (1 << k);
}
Insert cell
setBit(5, 1) // 0111 ("7 in base 10")
Insert cell
Insert cell
function unsetBit(n, k) {
return n & ~(1 << k); // XOR
}
Insert cell
setBit(unsetBit(unsetBit(5, 0), 2), 5)
Insert cell
Insert cell
function toggleBit(n, k) {
return n ^ (1 << k);
}
Insert cell
Insert cell
Insert cell
function isPowerOf2(n) {
return 0 == (n & (n - 1)); // two's complement, test for overlap
}
Insert cell
Insert cell
Insert cell
function highestOrderBit(n) {
let test = 31;
if (n == 0) return -1;
while (test > 0) {
if (n & (1 << test)) {
return test;
}
test--;
}
}
Insert cell
highestOrderBit(17) // 10001
Insert cell
highestOrderBit(32) // 100000
Insert cell
highestOrderBit(35) // 100011
Insert cell
// Unsigned integer. Assume 32 bits unsigned integer.
// A kind of cheeky solution that uses parseInt and toString with
// a binary radix specified.
function reverseBits(n) {
const BIT_SIZE = 32;
let s = n.toString(2);
for (let i = BIT_SIZE - s.length; i > 0; i--) {
s = "0" + s; // left pad zeros;
}
return parseInt(s.split('').reverse().join(''), 2);
}
Insert cell
highestOrderBit(43261596) // 00000010100101000001111010011100 in binary, 32 bits in total
Insert cell
reverseBits(43261596)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more