@thi.ng/hex
Version:
Hex string formatters for 4/8/16/24/32/48/64bit words, hexdump formatting of binary data
77 lines (76 loc) • 2.15 kB
JavaScript
const P32 = 4294967296;
const HEX = "0123456789abcdef";
const U4 = (x) => HEX[x & 15];
const U8 = (x) => HEX[x >>> 4 & 15] + HEX[x & 15];
const U8A = (x, i) => U8(x[i]);
const U16 = (x) => U8(x >>> 8) + U8(x & 255);
const U16BE = (x, i) => U8(x[i]) + U8(x[i + 1]);
const U16LE = (x, i) => U8(x[i + 1]) + U8(x[i]);
const U24 = (x) => U8(x >>> 16) + U16(x);
const U24BE = (x, i) => U8(x[i]) + U16BE(x, i + 1);
const U24LE = (x, i) => U8(x[i + 2]) + U16LE(x, i);
const U32 = (x) => U16(x >>> 16) + U16(x);
const U32BE = (x, i) => U16BE(x, i) + U16BE(x, i + 2);
const U32LE = (x, i) => U16LE(x, i + 2) + U16LE(x, i);
const U48 = (x) => U48HL(x / P32, x % P32);
const U48HL = (hi, lo) => U16(hi) + U32(lo);
const U48BE = (x, i) => U16BE(x, i) + U32BE(x, i + 2);
const U48LE = (x, i) => U16LE(x, i + 4) + U32LE(x, i);
const U64 = (x) => U64HL(x / P32, x % P32);
const U64BIG = (x) => U64HL(Number(x >> BigInt(32)), Number(x & BigInt(P32 - 1)));
const U64HL = (hi, lo) => U32(hi) + U32(lo);
const U64BE = (x, i) => U32BE(x, i) + U32BE(x, i + 4);
const U64LE = (x, i) => U32LE(x, i + 4) + U32LE(x, i);
const uuid = (id, i = 0) => (
// prettier-ignore
`${U32BE(id, i)}-${U16BE(id, i + 4)}-${U16BE(id, i + 6)}-${U16BE(id, i + 8)}-${U48BE(id, i + 10)}`
);
const hexdump = (bytes, addr, len, width, ascii) => hexdumpLines(bytes, addr, len, width, ascii).join("\n");
const hexdumpLines = (bytes, addr, len, width = 16, ascii = true) => {
len = Math.min(len, bytes.length - addr);
let res = [];
while (len > 0) {
const row = [...bytes.subarray(addr, addr + Math.min(len, width))];
const pad = len < width && ascii ? new Array(width - len).fill(" ") : [];
res.push(
[
U32(addr),
...row.map(U8),
...pad,
row.map(
(x) => x >= 32 && x < 128 ? String.fromCharCode(x) : "."
).join("")
].join(" ")
);
addr += width;
len -= width;
}
return res;
};
export {
HEX,
U16,
U16BE,
U16LE,
U24,
U24BE,
U24LE,
U32,
U32BE,
U32LE,
U4,
U48,
U48BE,
U48HL,
U48LE,
U64,
U64BE,
U64BIG,
U64HL,
U64LE,
U8,
U8A,
hexdump,
hexdumpLines,
uuid
};