Guest User

Untitled

a guest
Jan 17th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. // This is what I'm trying to implement:
  2. //
  3. // A function which takes raw data (ArrayBuffer) and
  4. // returns the data as a raw "binary" string,
  5. // just as you would get if you used FileReader.readAsBinaryString().
  6. function BytesToString(bytes) {
  7. return String.fromCharCode.apply(null, new Uint8Array(bytes));
  8. }
  9.  
  10. // Working with a small buffer works fine:
  11. const smallData = new Uint8Array([
  12. 72, // 'H'
  13. 101, // 'e'
  14. 108, // 'l'
  15. 108, // 'l'
  16. 111, // 'o'
  17. 33, // '!'
  18. 0, // raw byte 0x00
  19. 238, // raw byte 0xEE
  20. ]);
  21. console.log(smallData);
  22. console.log(BytesToString(smallData));
  23.  
  24. // The problem is it falls apart for larger buffers,
  25. // even if the size is still "reasonable" (2**20 == one megabyte)
  26. //
  27. // In Chrome this results in the somewhat-misleading error,
  28. // "Unhandled Rejection (RangeError): Maximum call stack size exceeded".
  29. //
  30. // This is disabled in order to show the rest of the example without a crash.
  31. // Change "false" to "true" to enable it:
  32. const showIssue = false;
  33. if (showIssue) {
  34. var bigData = new ArrayBuffer(2**20);
  35. var bigDataBytes = new Uint8Array(bigData);
  36. for (var i = 0; i < bigData.byteLength; ++i) {
  37. bigDataBytes[i] = 88; // 'X'
  38. }
  39. console.log(bigDataBytes);
  40. console.log(BytesToString(bigData));
  41. }
  42.  
  43. // As an alternative I tried to use TextEncoder/TextDecoder, but
  44. // the encoder thinks the data should be written as a list of numbers
  45. // and not as a raw string. (I don't really like this method anyway
  46. // because it introduces a needless encoding to UTF-8 and then
  47. // decoding back to the original code points.)
  48. var encoder = new TextEncoder();
  49. var decoder = new TextDecoder();
  50. const encoding = encoder.encode(smallData);
  51. const decoding = decoder.decode(encoding);
  52. console.log(encoding);
  53. console.log(decoding);
  54.  
  55. // I can't simply use TextDecoder alone, because it mis-interprets
  56. // the input as being UTF-8 encoded. Because the raw byte 0xEE is not
  57. // a valid UTF-8 sequence, the last character is replaced by the "Unicode
  58. // replacement character (�)":
  59. console.log(decoder.decode(smallData));
Add Comment
Please, Sign In to add comment