Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF-8 to UTF-16LE Javascript

I need to convert an utf-8 string to utf-16LE in javascript like the iconv() php function.

Ie:

iconv("UTF-8", "UTF-16LE", $string);

The output should be like this:

49 00 6e 00 64 00 65 00 78 00

I found this func to decode UTF-16LE and it's works fine but i don't know how to do the same to encode.

function decodeUTF16LE( binaryStr ) {
    var cp = [];
    for( var i = 0; i < binaryStr.length; i+=2) {
        cp.push( 
             binaryStr.charCodeAt(i) |
            ( binaryStr.charCodeAt(i+1) << 8 )
        );
    }

    return String.fromCharCode.apply( String, cp );
}

The conclusion is to create a binary file that can be downloaded.

The code:

function download(filename, text) {
    var a = window.document.createElement('a');

    var byteArray = new Uint8Array(text.length);
    for (var i = 0; i < text.length; i++) {
        byteArray[i] = text.charCodeAt(i) & 0xff;
    }
    a.href = window.URL.createObjectURL(new Blob([byteArray.buffer], {'type': 'application/type'}));

    a.download = filename;

    // Append anchor to body.
    document.body.appendChild(a);
    a.click();

    // Remove anchor from body
    document.body.removeChild(a);
}
like image 814
Keveun Avatar asked Jun 24 '14 06:06

Keveun


1 Answers

This should do it:

var byteArray = new Uint8Array(text.length * 2);
for (var i = 0; i < text.length; i++) {
    byteArray[i*2] = text.charCodeAt(i) // & 0xff;
    byteArray[i*2+1] = text.charCodeAt(i) >> 8 // & 0xff;
}

It's the inverse of your decodeUTF16LE function. Notice that neither works with code points outside of the BMP.

like image 57
Bergi Avatar answered Oct 18 '22 04:10

Bergi