最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

string - Printing the contents of a Javascript Uint8Array as raw bytes - Stack Overflow

programmeradmin5浏览0评论

I have a Uint8Array in Javascript that I would like to print the contents of to the console, eg

255, 19, 42, 0

This is my code, which currently prints an empty string

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

I can see the data in the debugger if I set a breakpoint, so bytes is definitely getting filled. When I tried printing via another method, it converted all the bytes to ASCII, but my data is mostly outside of the ASCII printable range.

Is there an equivalent to printf() in JavaScript?

I have a Uint8Array in Javascript that I would like to print the contents of to the console, eg

255, 19, 42, 0

This is my code, which currently prints an empty string

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

I can see the data in the debugger if I set a breakpoint, so bytes is definitely getting filled. When I tried printing via another method, it converted all the bytes to ASCII, but my data is mostly outside of the ASCII printable range.

Is there an equivalent to printf() in JavaScript?

Share Improve this question edited Sep 25, 2014 at 18:17 amo asked Sep 22, 2014 at 1:28 amoamo 4,3405 gold badges32 silver badges42 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

The concat method doesn't act like a buffer that you can append to, but rather returns a new string.

Therefore, you have to assign the result of concat to your result string on every invocation:

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

Implemented like this, your debugBytes string will end up containing a ma-separated list of the byte values.


A more concise solution is to convert your Uint8Array to a regular Javascript array, and then use the join method:

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

There's no printf method in the current ECMAScript standard, there are however a number of custom implementations. See this question for some suggestions.

发布评论

评论列表(0)

  1. 暂无评论