UTF-8 到 UTF-16LE Javascript

Kev*_*eun 5 javascript encoding utf-8 utf-16

我需要在 javascript 中将 utf-8 字符串转换为 utf-16LE,如 iconv() php 函数。

IE:

iconv("UTF-8", "UTF-16LE", $string);
Run Code Online (Sandbox Code Playgroud)

输出应该是这样的:

49 00 6e 00 64 00 65 00 78 00

我发现这个 func 可以解码 UTF-16LE,它工作正常,但我不知道如何做同样的编码。

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 );
}
Run Code Online (Sandbox Code Playgroud)

结论是创建一个可以下载的二进制文件。

编码:

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);
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 6

这应该这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

它与你的decodeUTF16LE功能相反。请注意,两者都不适用于 BMP 之外的代码点。