Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 449
Van Coding Avatar asked Jan 25 '12 16:01

Van Coding


1 Answers

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++]);
}
like image 195
Van Coding Avatar answered Nov 02 '22 07:11

Van Coding