UTF-8到UTF-16LE Javascript [英] UTF-8 to UTF-16LE Javascript
本文介绍了UTF-8到UTF-16LE Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在javascript中将utf-8字符串转换为utf-16LE,例如iconv()php函数。
I need to convert an utf-8 string to utf-16LE in javascript like the iconv() php function.
即:
iconv("UTF-8", "UTF-16LE", $string);
输出应如下所示:
49 00 6e 00 64 00 65 00 78 00
49 00 6e 00 64 00 65 00 78 00
我发现这个函数可以解码UTF-16LE
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.
代码:
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);
}
推荐答案
这应该做到:
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;
}
这是您的 decodeUTF16LE $ c的反函数$ c>函数。请注意,这两个代码均不适用于BMP之外的代码点。
It's the inverse of your decodeUTF16LE
function. Notice that neither works with code points outside of the BMP.
这篇关于UTF-8到UTF-16LE Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文