dovhpmnm31216 2014-06-23 22:09
浏览 808
已采纳

UTF-8到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);
}

展开全部

  • 写回答

2条回答 默认 最新

  • dougaicha5258 2014-06-24 04:32
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部