How to use strings with JavaScript Typed Arrays

Adam M-W picture Adam M-W · Nov 16, 2011 · Viewed 7.2k times · Source

I've come across a problem in that I don't see a way to easily convert strings to typed arrays, and converting from typed arrays to strings appears to be a real pain requiring a manual char code conversion for every byte. Is there any better methods to convert strings to typed arrays or vise-versa?

Example:

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

Answer

kongaraju picture kongaraju · Sep 27, 2012

This should solve your problem

How to use strings with JavaScript Typed Arrays

JS Strings are stored in UTF-16 encoding where each character takes 2 bytes. String.charCodeAt returns these 2-byte Unicodes. This is 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 string 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;
     }