Skip to content

Instantly share code, notes, and snippets.

@jawj
Last active November 12, 2024 17:09
Show Gist options
  • Save jawj/760acc7fa499f309e2e2475377e4faf3 to your computer and use it in GitHub Desktop.
Save jawj/760acc7fa499f309e2e2475377e4faf3 to your computer and use it in GitHub Desktop.
Fast hex encoding in JS using (roughly) Duff's device
const
toHexDecoder = new TextDecoder(),
charCodes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102], // 0123456789abcdef
u16Lookup = new Uint16Array(256),
isLittleEndian = new Uint8Array((new Uint16Array([0x0102]).buffer))[0] === 0x02;
if (isLittleEndian) for (let i = 0; i < 256; i ++) u16Lookup[i] = charCodes[i & 0xF] << 8 | charCodes[(i >>> 4) & 0xF];
else for (let i = 0; i < 256; i ++) u16Lookup[i] = charCodes[i & 0xF] | charCodes[(i >>> 4) & 0xF] << 8;
export function toHex(data) {
const
len = data.length,
last7 = len - 7,
out = new Uint16Array(len);
let i = 0;
while (i < last7) {
out[i] = u16Lookup[data[i++]];
out[i] = u16Lookup[data[i++]];
out[i] = u16Lookup[data[i++]];
out[i] = u16Lookup[data[i++]]; // 4
out[i] = u16Lookup[data[i++]];
out[i] = u16Lookup[data[i++]];
out[i] = u16Lookup[data[i++]];
out[i] = u16Lookup[data[i++]]; // 8
}
while (i < len) {
out[i] = u16Lookup[data[i++]];
}
return toHexDecoder.decode(out);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment