Skip to content

Javascript ascii string to hex byte array

I am trying to convert an ASCII string into a byte array.

Problem is my code is converting from ASCII to a string array and not a Byte array:

var tx = '[86400:?]';
for (a = 0; a < tx.length; a = a + 1) {
    hex.push('0x'+tx.charCodeAt(a).toString(16));
}

This results in:

 [ '0x5b','0x38','0x36','0x30','0x30','0x30','0x3a','0x3f','0x5d' ]

But what I am looking for is:

[0x5b,0x38 ,0x30 ,0x30 ,0x30 ,0x30 ,0x3a ,0x3f,0x5d]

How can I convert to a byte rather than a byte string ?

This array is being streamed to a USB device:

device.write([0x5b,0x38 ,0x30 ,0x30 ,0x30 ,0x30 ,0x3a ,0x3f,0x5d])

And it has to be sent as one array and not looping sending device.write() for each value in the array.

Answer

A single liner :

   '[86400:?]'.split ('').map (function (c) { return c.charCodeAt (0); })

returns

    [91, 56, 54, 52, 48, 48, 58, 63, 93]

This is, of course, is an array of numbers, not strictly a “byte array”. Did you really mean a “byte array”?

Split the string into individual characters then map each character to its numeric code.

Per your added information about device.write I found this :

Writing to a device

Writing to a device is performed using the write call in a device handle. All writing is synchronous.

device.write([0x00, 0x01, 0x01, 0x05, 0xff, 0xff]);

on https://npmjs.org/package/node-hid

Assuming this is what you are using then my array above would work perfectly well :

device.write('[86400:?]'.split ('').map (function (c) { return c.charCodeAt (0); }));

As has been noted the 0x notation is just that, a notation. Whether you specify 0x0a or 10 or 012 (in octal) the value is the same.