How to use strings using JavaScript Typed Arrays

I ran into a problem in that I see no way to easily convert strings to typed arrays, and converting from typed arrays to strings seems like a real pain, requiring a manual conversion of the char code for each byte. Are there any better methods for converting strings to typed arrays or vice versa?

Example:

I have a UTF8 encoded string, "Something or the other," and I want to write it to an ArrayBuffer in length, and then in string format.

+4
source share
3 answers

This should solve your problem.

How to use strings with typed JavaScript arrays

JS strings are stored in UTF-16 encoding, where each character takes 2 bytes. String.charCodeAt returns these 2-byte Unicodes. Here's how to read UTF-16 encoded strings from a DataView:

DataView.prototype.getUTF16String = function(offset, length) { var utf16 = new ArrayBuffer(length * 2); var utf16View = new Uint16Array(utf16); for (var i = 0; i < length; ++i) { utf16View[i] = this.getUint8(offset + i); } return String.fromCharCode.apply(null, utf16View); }; 

and these functions to convert strings to and from arraybuffer

  function ab2str(buf) { return String.fromCharCode.apply(null, new Uint16Array(buf)); } function str2ab(str) { var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char var bufView = new Uint16Array(buf); for (var i=0, strLen=str.length; i<strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; } 
+2
source

You can use TextEncoder and TextDecoder , which currently seem to be implemented only in Firefox. These are two full years after your initial question :)

Fortunately, there is a polyfill that does the job.

 var initialString = "Something or other"; var utf8EncodedString = new TextEncoder("utf-8").encode(initialString); // utf8EncodedString is a Uint8Array, so you can inspect // the individual bytes directly: for (var i = 0; i < utf8EncodedString.length; ++i) { console.log(utf8EncodedString[i]); } var decodedString = new TextDecoder("utf-8").decode(utf8EncodedString); if (initialString !== decodedString) { console.error("You're lying!"); } 
+1
source

If you want to use external libraries, you can look at jDataView , which supports reading strings in different encodings from TypedArray and also handles content conversion.

0
source

Source: https://habr.com/ru/post/1381505/


All Articles