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.

Revisions

  1. guest271314 revised this gist Aug 17, 2025. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions hex-from-array.md
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    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`
  2. guest271314 created this gist Aug 15, 2025.
    40 changes: 40 additions & 0 deletions hex-from-array.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    > 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:
    ```js
    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
    ```js
    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);
    ```