@moon7/bits
Version:
Type-safe bitwise operations for JavaScript and TypeScript with named bit collections
88 lines (87 loc) • 1.98 kB
JavaScript
const ALL = -1 >>> 0;
const NONE = 0;
function bitMask(i) {
return 1 << i >>> 0;
}
function checkMask(bits, mask) {
return (bits & mask) !== 0;
}
function applyMask(bits, mask) {
return (bits | mask) >>> 0;
}
function clearMask(bits, mask) {
return bits & ~mask;
}
function toggleMask(bits, mask) {
return (bits ^ mask) >>> 0;
}
function getBit(bits, index) {
return checkMask(bits, bitMask(index));
}
function setBit(bits, index, value) {
return value ? setBitOn(bits, index) : setBitOff(bits, index);
}
function setBitOn(bits, index) {
return applyMask(bits, bitMask(index));
}
function setBitOff(bits, index) {
return clearMask(bits, bitMask(index));
}
function toggleBit(bits, index) {
return toggleMask(bits, bitMask(index));
}
function toBinaryString(bits, length = 32) {
return bits.toString(2).padStart(length, "0");
}
function toFormattedBinaryString(bits, length = 32) {
var _a;
const str = toBinaryString(bits, length);
return ((_a = str.match(/.{1,8}/g)) == null ? void 0 : _a.map((x) => {
var _a2;
return (_a2 = x.match(/.{1,4}/g)) == null ? void 0 : _a2.join(" ");
}).join(" - ")) ?? "";
}
function countBits(bits) {
let count = 0;
let value = bits;
while (value) {
count += value & 1;
value >>>= 1;
}
return count;
}
function isSingleBit(bits) {
return bits !== 0 && (bits & bits - 1) === 0;
}
function defineBitFlags(definition) {
const result = { ...definition };
result.mask = (name) => bitMask(result[name]);
return result;
}
function defineBitEnum(...names) {
const result = {};
names.forEach((name, index) => result[name] = index);
result.mask = (name) => bitMask(result[name]);
return result;
}
export {
ALL,
NONE,
applyMask,
bitMask,
checkMask,
clearMask,
countBits,
defineBitEnum,
defineBitFlags,
getBit,
isSingleBit,
setBit,
setBitOff,
setBitOn,
toBinaryString,
toFormattedBinaryString,
toggleBit,
toggleMask
};
//# sourceMappingURL=index.js.map