将Javascript Uint8Array的内容打印为原始字节

Printing the contents of a Javascript Uint8Array as raw bytes

本文关键字:打印 原始 字节 Javascript Uint8Array      更新时间:2023-09-26

我有一个Javascript中的Uint8Array,我想将其内容打印到控制台,例如

255, 19, 42, 0

这是我的代码,它当前打印一个空字符串

    var bytes = new Uint8Array(data);
    var debugBytes = "";
    for(var i=0; i<bytes.byteLength; i++) {
        debugBytes.concat(bytes[i].toString());
        debugBytes.concat(",");
    }
    console.log('Processing packet [' + bytes[1] + '] ' + debugBytes);

如果我设置了一个断点,我可以在调试器中看到数据,所以字节肯定会被填满。当我尝试通过另一种方法打印时,它将所有字节转换为ASCII,但我的数据大多在ASCII可打印范围之外。

在JavaScript中有类似printf()的功能吗?

concat方法的作用不像可以附加到的缓冲区,而是返回一个新字符串。

因此,您必须在每次调用时将concat的结果分配给您的结果字符串:

 debugBytes = debugBytes.concat(bytes[i].toString());
 debugBytes = debugBytes.concat(",");

这样实现,debugBytes字符串最终将包含一个以逗号分隔的字节值列表。


一个更简洁的解决方案是将Uint8Array转换为常规Javascript数组,然后使用join方法:

console.log(Array.apply([], bytes).join(","));

在当前的ECMAScript标准中没有printf方法,但是有许多自定义实现。请参阅此问题以获取一些建议。