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

时间:2014-09-22 01:28:40

标签: javascript string binary-data

我在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()等效的内容?

1 个答案:

答案 0 :(得分:4)

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

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

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

如此实现,您的debugBytes字符串最终将包含以逗号分隔的字节值列表。


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

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

当前ECMAScript标准中没有printf方法,但是有许多自定义实现。有关建议,请参阅此question