0

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.

Lee
  • 29,398
  • 28
  • 117
  • 170
  • 2
    There's nothing [in MDN's documentation to indicate that it would](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/toString)... And that answer has a `toHexString` function for that purpose. – Heretic Monkey Jan 22 '21 at 19:05
  • 1
    `toString('hex')`? It [doesn't take an argument](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/toString)`... – trincot Jan 22 '21 at 19:09
  • @trincot True, I've updated the question and will continue to as I attempt to get to bottom of it... – Lee Jan 22 '21 at 19:14
  • @trincot note I think I was looking at a browserifed nodejs [`Buffer`](https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end) object not a true TypedArray. Thank you – Lee Jan 22 '21 at 19:32

1 Answers1

3

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));
trincot
  • 317,000
  • 35
  • 244
  • 286