From discord, AssemblyScript channel
guest271314 Let's say you have a
TypedArray
such asvar u = Uint8Array.of(49, 48, 48, 48)
and you know those values in hexidecimal will produce an integerparseInt(new TextDecoder().decode(u), 16) // 4096
. How can that4096
be derived without converting to a string, usingDataView
or other methods to get the integer?
PhoenixIllusion case insensitive ascii-to-hex could be brute forced via:
function hexFromArray(a) {
let total = 0;
for(let i=0;i<a.length;i++) {
hex = a[i];
const intVal = hex > 96 ? hex - 87 : hex > 64 ? hex - 55 : hex - 48;
total = intVal + (total << 4);
}
return total;
}
or taking advantage of the fact the lower 4 bits of both '0', 'a', and 'A' are fairly clean, for
0-9
= ascii & 0xF fora-f
orA-F
= (ascii & 0xF) + 9
function hexFromArray(a) {
let total = 0;
for(let i=0;i<a.length;i++) {
let hex = a[i];
let intVal = hex & 0xF;
if (hex > 64) intVal += 9;
total = intVal + (total << 4);
}
return total;
}
pretty sure this isn't more efficient since trading a conditional jump for a 100% always triggering shift+multiply+add, but branchless
const hex = a[i];
const intVal = hex & 0xF;
const a_f = (hex >> 6) * 9;
total = (intVal + a_f) + (total << 4);