Search code examples
javascriptarrayshexparseintuint8array

Why doesn't Uint8Array.toString('hex') return hex?


Given this (based on another answer):

const fromHexString = hexString => new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));

console.log(fromHexString('a0e30c9e46d8f973f4082d79fce1fb46b1c199bb047bb3545c85b545f7a1650a').toString('hex'))

//expected "a0e30c9e46d8f973f4082d79fce1fb46b1c199bb047bb3545c85b545f7a1650a"

//get "160,227,12,158,70,216,249,115,244,8,45,121,252,225,251,70,177,193,153,187,4,123,179,84,92,133,181,69,247,161,101,10"

Why does it not return as hex?

Edit, the source of my confusion. I'm using the hypersdk library. This allows for .toString('hex') pattern.

When I switch to beaker I can no longer use it.

Edit 2:

I think my confusion arose because what I was using was based on node.js's Buffer object: https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end

This was browserified using hypersdk in such a way that the buffer is represented as a TypedArray object with the toString prototype method overwritten to match the Buffer version.


Solution

  • A typed array has a toString method that takes no argument, so providing 'hex' to it will have no influence, it will just join the values into a comma-separated list of the values in decimal representation.

    To get hexadecimal output, you'll need to iterate the array and convert each value to hex and concatenate the result:

    const fromHexString = hexString => new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
    
    const toHexString = arr => Array.from(arr, i => i.toString(16).padStart(2, "0")).join("");
    
    const arr = fromHexString('a0e30c9e46d8f973f4082d79fce1fb46b1c199bb047bb3545c85b545f7a1650a');
    
    console.log(toHexString(arr));