@thi.ng/base-n
Version:
Arbitrary base-n conversions w/ presets for base8/16/32/36/58/62/64/83/85, support for bigints and encoding/decoding of byte arrays
52 lines (51 loc) • 1.31 kB
JavaScript
import { B16_LC_CHARS } from "./chars/16.js";
const MAX_SAFE_INT = BigInt(2 ** 53 - 1);
class BaseNEncoder {
constructor(base) {
this.base = base;
this.N = base.length;
}
N;
__pc = [];
clear() {
this.__pc.length = 0;
}
encode(x, size = 0) {
const { base, N } = this;
if (x === 0) return this.__pad(base[0], size);
let res = "";
while (x > 0) {
res = base[x % N] + res;
x = Math.floor(x / N);
}
return this.__pad(res, size);
}
encodeBigInt(x, size = 0) {
if (x <= MAX_SAFE_INT) return this.encode(Number(x), size);
const { base, N } = this;
if (x === 0n) return this.__pad(base[0], size);
const NN = BigInt(N);
let res = "";
while (x > 0n) {
res = base[Number(x % NN)] + res;
x /= NN;
}
return this.__pad(res, size);
}
encodeBytes(buf, size = 0) {
let hex = "0x";
for (let i = 0, n = buf.length; i < n; i++) hex += __u8(buf[i]);
return this.encodeBigInt(BigInt(hex), size);
}
size(x) {
return Math.ceil(Math.log(x) / Math.log(this.N));
}
__pad(x, size) {
const d = size - x.length;
return d > 0 ? (this.__pc[d] || (this.__pc[d] = this.base[0].repeat(d))) + x : x;
}
}
const __u8 = (x) => B16_LC_CHARS[x >>> 4 & 15] + B16_LC_CHARS[x & 15];
export {
BaseNEncoder
};