extra-bit
Version:
The bit is a basic unit of information in information theory, computing.
114 lines (111 loc) • 2.86 kB
JavaScript
;
function ones(w) {
return (1 << w) - 1;
}
function get(x, i, w = 1) {
return (x >>> i) & ones(w);
}
function getAs(x, m) {
return x & m;
}
function set(x, i, v = 1, w = 1) {
return (x & ~(ones(w) << i)) | (v << i);
}
function setAs(x, m, f = 1) {
return (x & ~m) | (-f & m);
}
function toggle(x, i, w = 1) {
return x ^ (ones(w) << i);
}
function toggleAs(x, m) {
return x ^ m;
}
function swap(x, i, j, w = 1) {
var t = ((x >>> i) ^ (x >>> j)) & ones(w);
return x ^ ((t << i) | (t << j));
}
const MOD37_POS32 = [
32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4, 7, 17, 0,
25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18
];
function scan(x) {
return MOD37_POS32[(-x & x) % 37];
}
const DEBRUIJN_POS32 = [
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
];
function scanReverse(x) {
x |= x >>> 1;
x |= x >>> 2;
x |= x >>> 4;
x |= x >>> 8;
x |= x >>> 16;
return DEBRUIJN_POS32[(x * 0x07C4ACDD) >>> 27];
}
function count(x) {
x = x - ((x >>> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >>> 2) & 0x33333333);
return ((x + (x >>> 4) & 0x0F0F0F0F) * 0x01010101) >>> 24;
}
function parity1(x) {
x ^= x >>> 16;
x ^= x >>> 8;
x ^= x >>> 4;
x &= 0xF;
return (0x6996 >>> x) & 1;
}
function parity(x, n = 1) {
if (n === 1)
return parity1(x);
var m = (1 << n) - 1, a = 0 | 0;
while (x) {
a ^= x & m;
x >>>= n;
}
return a;
}
function rotate(x, n = 0) {
return n < 0 ? x << 32 + n | x >>> -n : x << n | x >> 32 - n;
}
function reverse(x) {
x = ((x >>> 1) & 0x55555555) | ((x & 0x55555555) << 1);
x = ((x >>> 2) & 0x33333333) | ((x & 0x33333333) << 2);
x = ((x >>> 4) & 0x0F0F0F0F) | ((x & 0x0F0F0F0F) << 4);
x = ((x >>> 8) & 0x00FF00FF) | ((x & 0x00FF00FF) << 8);
return (x >>> 16) | (x << 16);
}
function merge(x, y, m) {
return x ^ ((x ^ y) & m);
}
function interleave(x, y) {
x = (x | (x << 8)) & 0x00FF00FF;
x = (x | (x << 4)) & 0x0F0F0F0F;
x = (x | (x << 2)) & 0x33333333;
x = (x | (x << 1)) & 0x55555555;
y = (y | (y << 8)) & 0x00FF00FF;
y = (y | (y << 4)) & 0x0F0F0F0F;
y = (y | (y << 2)) & 0x33333333;
y = (y | (y << 1)) & 0x55555555;
return y | (x << 1);
}
function signExtend(x, w = 32) {
w = 32 - w;
return (x << w) >> w;
}
exports.count = count;
exports.get = get;
exports.getAs = getAs;
exports.interleave = interleave;
exports.merge = merge;
exports.parity = parity;
exports.reverse = reverse;
exports.rotate = rotate;
exports.scan = scan;
exports.scanReverse = scanReverse;
exports.set = set;
exports.setAs = setAs;
exports.signExtend = signExtend;
exports.swap = swap;
exports.toggle = toggle;
exports.toggleAs = toggleAs;