dovhpmnm31216 2014-06-24 06: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 12: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条)

报告相同问题?

悬赏问题

  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?