const testLength = 4100;
const value = new Uint8Array(testLength);
for (let i = 0; i < testLength; i ++) value[i] = (Math.random() * 255) << 0;
let checkString = '';
for (let i = 0; i < testLength; i ++) {
const v = value[i];
checkString += (v < 16 ? '0' : '') + v.toString(16);
}
const hexPairs = new Array(256);
for (let i = 0; i < 256; i++) hexPairs[i] = (i < 16 ? '0' : '') + i.toString(16);
function toHex(data) {
const len = data.length;
let
out = '',
i = 0;
while (i < len) out += hexPairs[data[i++]];
return out;
}
if (toHex(value) !== checkString) throw new Error('Bad result');
for (let i = 0; i < 10000; i ++) toHex(value);
const hexPairs = new Array(256);
for (let i = 0; i < 256; i++) hexPairs[i] = (i < 16 ? '0' : '') + i.toString(16);
function toHex(data) {
const
len = data.length,
last7 = len - 7;
let
out = '',
i = 0;
while (i < last7) {
out += hexPairs[data[i++]];
out += hexPairs[data[i++]];
out += hexPairs[data[i++]];
out += hexPairs[data[i++]]; // 4
out += hexPairs[data[i++]];
out += hexPairs[data[i++]];
out += hexPairs[data[i++]];
out += hexPairs[data[i++]]; // 8
}
while (i < len) {
out += hexPairs[data[i++]];
}
return out;
}
if (toHex(value) !== checkString) throw new Error('Bad result');
for (let i = 0; i < 10000; i ++) toHex(value);
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;
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);
}
if (toHex(value) !== checkString) throw new Error('Bad result');
for (let i = 0; i < 10000; i ++) toHex(value);