0

const stringArray = ['0x00','0x3c','0xbc]

to

const array = [0x00,0x3c,0bc]

var buf = new Buffer.from(array)

How should I go about using the buffers in the string above as buffers?

  • 1
    You may want to use something like this: `Buffer.from(['0x00','0x3c','0xbc'].map(e => +e)));` – stacj Feb 21 '22 at 10:33

1 Answers1

0

You appear to have an array of strings where the strings are byte values written as hexadecimal strings. So you need to:

  • Convert each hex string to a byte; that's easily done with parseInt(str, 16) (the 16 being hexadecimal). parseInt will allow the 0x prefix. Or you could use +str or Number(str) since the prefix is there to tell them what number base to use. (More about various ways to convert strings to numbers in my answer here.)
  • Create a buffer and fill it in with the bytes.

If the array isn't massive and you can happily create a temporary array, use map and Buffer.from:

const buffer = Buffer.from(theArray.map(str => +str)));

If you want to avoid any unnecessary intermediate arrays, I'm surprised not to see any variant of Buffer.from that allows mapping, so we have to do those things separately:

const buffer = Buffer.alloc(theArray.length);
for (let index = 0; index < theArray.length; ++index) {
    buffer[index] = +theArray[index];
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875