Skip to content
Advertisement

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:

JavaScript

This results in:

JavaScript

But what I am looking for is:

JavaScript

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

This array is being streamed to a USB device:

JavaScript

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

Advertisement

Answer

A single liner :

JavaScript

returns

JavaScript

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 :

JavaScript

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement