Looking for a performant algorithm for parsing any-length hexadecimal strings into Uint8Arrays. I specifically care about use with Chrome and Firefox's engines.
A common approach used in code snippets:
function hex2bytes(string) {
const normal = string.length % 2 ? "0" + string : string; // Make even length
const bytes = new Uint8Array(normal.length / 2);
for (let index = 0; index < bytes.length; ++index) {
bytes[index] = parseInt(normal.substr(index, 2), 16); // Parse each pair
}
return bytes;
}
Another common (bad) approach is to split the string using the regular expression /[\dA-F]{2}/gi
and iterate over the matches with parseInt
.
I've found a much faster algorithm using charCodeAt
:
function hex2bytes(string) {
const normal = string.length % 2 ? "0" + string : string; // Make even length
const bytes = new Uint8Array(normal.length / 2);
for (let index = 0; index < bytes.length; ++index) {
const c1 = normal.charCodeAt(index * 2);
const c2 = normal.charCodeAt(index * 2 + 1);
const n1 = c1 - (c1 < 58 ? 48 : 87);
const n2 = c2 - (c2 < 58 ? 48 : 87);
bytes[index] = n1 * 16 + n2;
}
return bytes;
}
Can I do better?