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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16893817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:23:50  来源:igfitidea点击:

Javascript ascii string to hex byte array

javascriptarraysnode.js

提问by crankshaft

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()。

回答by HBP

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.writeI found this :

根据您添加的有关device.write我发现的信息:

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]);

写入设备

写入设备是使用设备句柄中的 write 调用来执行的。所有写入都是同步的。

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

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

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 0xnotation is just that, a notation. Whether you specify 0x0aor 10or 012(in octal) the value is the same.

正如已经指出的那样,0x符号就是一个符号。无论您指定0x0aor10012(八进制)值都是相同的。