简体   繁体   English

Javascript ascii 字符串到十六进制字节数组

[英]Javascript ascii string to hex byte array

I am trying to convert an ASCII string into a byte array.我正在尝试将 ASCII 字符串转换为字节数组。

Problem is my code is converting from ASCII to a string array and not a Byte array:问题是我的代码正在从 ASCII 转换为字符串数组而不是字节数组:

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:此数组正在流式传输到 USB 设备:

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.它必须作为一个数组发送,而不是为数组中的每个值循环发送 device.write()。

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 :根据您添加的有关device.write信息,我发现了这一点:

Writing to a device写入设备

Writing to a device is performed using the write call in a device handle.写入设备是使用设备句柄中的 write 调用来执行的。 All writing is synchronous.所有写入都是同步的。

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

on https://npmjs.org/package/node-hidhttps://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.如前所述, 0x表示法只是一种表示法。 Whether you specify 0x0a or 10 or 012 (in octal) the value is the same.无论您指定0x0a还是10012 (八进制),该值都是相同的。

   function getBytes(str){
       let intArray=str.split ('').map (function (c) { return c.charCodeAt (0); });
       let byteArray=new Uint8Array(intArray.length);
       for (let i=0;i<intArray.length;i++)
         byteArray[i]=intArray[i];
       return byteArray;
   }
   device.write(getBytes('[86400:?]'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM