Van Coding
Van Coding

Reputation: 24554

Javascript - Converting between Unicode string and ArrayBuffer

Does somebody know a script that is able to convert a string to a ArrayBuffer using unicode encoding?

I´m creating a browser-side eqivalent of the "Buffer" of node.js. The only encoding that is left is unicode. All others are done.

Thanks for your help!

Upvotes: 5

Views: 9835

Answers (1)

Van Coding
Van Coding

Reputation: 24554

I found it out by myself.

Decoding:

var b = new Uint8Array(str.length*2);
for(var i = 0; i < b.length; i+=2){
    var x = str.charCodeAt(i/2);
    var a = x%256;
    x -= a;
    x /= 256;
    b[i] = x;
    b[i+1] = a;
}

Encoding

var s = "";
for(var i = 0; i < this.length;){
    s += String.fromCharCode(this[i++]*256+this[i++]);
}

Upvotes: 8

Related Questions