dovhpmnm31216 2014-06-24 06:09
浏览 807
已采纳

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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划