0

I found an elegant code to converts ArrayBuffer into charCode.

But I need char, instead of charCode.

function ab2s (buf) {
  var view = new Uint8Array (buf);
  return Array.prototype.join.call (view, ",");
}

I tried

return Array.prototype.join.call (view, function() {String.fromCharCode(this)});

But this is crap.

Thanks for answers.

4
  • What do you think is the difference between char and charcode? Can you please provide some example input, the expected output and what happens for you instead? Commented May 3, 2014 at 20:11
  • Why did you pass a callback function to Array::join? The only thing it takes is a delimiter! Commented May 3, 2014 at 20:12
  • Charcode (ASCII code) numbers 65 66 67 => A B C Commented May 3, 2014 at 20:37
  • I have to rewrite my question? Commented May 3, 2014 at 20:39

1 Answer 1

1
return Array.prototype.join.call (view, function() {String.fromCharCode(this)});

But this is crap.

Obviously, since Array::join does not take a callback to transform each element but only the separator by which the elements should be joined.

Instead, to transform every element before joining them you would use Array::map:

return Array.prototype.map.call(view, function(charcode) {
    return String.fromCharCode(charcode);
}).join('');

However, there is a much easier solution, as String.fromCharCode does take multiple arguments:

return String.fromCharCode.apply(String, view);
Sign up to request clarification or add additional context in comments.

9 Comments

Output in hex editor: Original : '00 00 9C BO 6D 6F | ....mo' From your script '00 00 C2 9C C2 B0 6D 6F | ......mo' Problem with ASCII code > 127 Second script have same output and limit 256kb string
You did not say anything about file I/O. I don't know what you're doing, but JS does use Unicode for its strings, so when writing to a file you usually get some UTF encoding.
1Byte (8bit) greater than 127 spread at 2bytes. Is it possible to somehow get around this?
Write as ASCII? As I said, those aren't "bytes", but Unicode "characters"! If you're just caring about binaries, then strings are the wrong tool to work with. If you've got further problems, please ask a new question and include the IO code there.
In JavaScript it looks OK, transformation occurs after sending to the server, so the solution is to adjust it in PHP. Is able this set in headers? Octet-stream?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.