Skip to content

Instantly share code, notes, and snippets.

@guest271314
Last active August 17, 2025 18:45
Show Gist options
  • Save guest271314/d6e932154e11fffb75fd7d1a4b25f4f5 to your computer and use it in GitHub Desktop.
Save guest271314/d6e932154e11fffb75fd7d1a4b25f4f5 to your computer and use it in GitHub Desktop.
Hex from array

From discord, AssemblyScript channel

guest271314 Let's say you have a TypedArray such as var u = Uint8Array.of(49, 48, 48, 48) and you know those values in hexidecimal will produce an integer parseInt(new TextDecoder().decode(u), 16) // 4096. How can that 4096 be derived without converting to a string, using DataView 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 for a-f or A-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);
@guest271314
Copy link
Author

Runtime | Deno 2.4.4+410c66a (x86_64-unknown-linux-gnu)

file:///home/user/hexFromArrayBench.js

| benchmark         | time/iter (avg) |        iter/s |      (min … max)      |      p75 |      p99 |     p995 |
| ----------------- | --------------- | ------------- | --------------------- | -------- | -------- | -------- |
| parseInt()        |        595.5 ns |     1,679,000 | (559.1 ns … 774.2 ns) | 602.8 ns | 774.2 ns | 774.2 ns |
| hexFromArray1()   |         43.7 ns |    22,870,000 | ( 36.9 ns …  94.8 ns) |  41.7 ns |  74.3 ns |  76.2 ns |
| hexFromArray2()   |         40.7 ns |    24,560,000 | ( 33.3 ns …  94.3 ns) |  39.0 ns |  72.7 ns |  77.8 ns |

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment