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.

bedna
  • 1,330
  • 11
  • 20

1 Answers1

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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 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 – bedna May 05 '14 at 18:29
  • 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. – Bergi May 05 '14 at 18:32
  • 1Byte (8bit) greater than 127 spread at 2bytes. Is it possible to somehow get around this? – bedna May 05 '14 at 18:37
  • 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](http://stackoverflow.com/questions/ask) and include the IO code there. – Bergi May 05 '14 at 18:46
  • 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? – bedna May 05 '14 at 18:53
  • No, you should send the correct headers on the client side. As I said, please post a new question and we will help you there. – Bergi May 05 '14 at 19:01
  • I solved this by converting again to ArrayBuffer before upload. – bedna May 07 '14 at 18:07
  • Huh? Why convert forth and back, instead of just sending what you have? – Bergi May 07 '14 at 18:08
  • Convert ArrayBuffer to byteString is only for encrypt string. – bedna May 07 '14 at 19:51