您的位置:首页 > Web前端 > JavaScript

javascript中string转UTF8格式byte数组

2015-06-17 16:29 591 查看
在javascript代码中,有些地方我们需要将string转为byte数组再进行进一步处理,网上太少这方面的资料。这里我根据java中String.getByte(“UTF-8”)的实现机制来进行string转byte数组的处理,同时解决中文和非英文字母转byte数组时的编码问题。其代码如下:
/**
*@description:将string转为UTF-8格式signed char字节数组
*
*/
function stringToBytes(str){
var bytes = new Array();
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
var s = parseInt(c).toString(2);
if(c >= parseInt("000080",16) && c <= parseInt("0007FF",16)){
var af = "";
for(var j = 0; j < (11 - s.length); j++){
af += "0";
}
af += s;
var n1 = parseInt("110" + af.substring(0,5),2);
var n2 = parseInt("110" + af.substring(5),2);
if(n1 > 127) n1 -= 256;
if(n2 > 127) n2 -= 256;
bytes.push(n1);
bytes.push(n2);
}else if(c >= parseInt("000800",16) && c <= parseInt("00FFFF",16)){
var af = "";
for(var j = 0; j < (16 - s.length); j++){
af += "0";
}
af += s;
var n1 = parseInt("1110" + af.substring(0,4),2);
var n2 = parseInt("10" + af.substring(4,10),2);
var n3 = parseInt("10" + af.substring(10),2);
if(n1 > 127) n1 -= 256;
if(n2 > 127) n2 -= 256;
if(n3 > 127) n3 -= 256;
bytes.push(n1);
bytes.push(n2);
bytes.push(n3);
}else if(c >= parseInt("010000",16) && c <= parseInt("10FFFF",16)){
var af = "";
for(var j = 0; j < (21 - s.length); j++){
af += "0";
}
af += s;
var n1 = parseInt("11110" + af.substring(0,3),2);
var n2 = parseInt("10" + af.substring(3,9),2);
var n3 = parseInt("10" + af.substring(9,15),2);
var n4 = parseInt("10" + af.substring(15),2);
if(n1 > 127) n1 -= 256;
if(n2 > 127) n2 -= 256;
if(n3 > 127) n3 -= 256;
if(n4 > 127) n4 -= 256;
bytes.push(n1);
bytes.push(n2);
bytes.push(n3);
bytes.push(n4);
}else{
bytes.push(c & 0xff);
}
}
return bytes;
}
这样,就完成了string通过UTF-8转byte数组。

经过算法可精简为以下代码:
function str2UTF8(str){
var bytes = new Array();
var len,c;
len = str.length;
for(var i = 0; i < len; i++){
c = str.charCodeAt(i);
if(c >= 0x010000 && c <= 0x10FFFF){
bytes.push(((c >> 18) & 0x07) | 0xF0);
bytes.push(((c >> 12) & 0x3F) | 0x80);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
}else if(c >= 0x000800 && c <= 0x00FFFF){
bytes.push(((c >> 12) & 0x0F) | 0xE0);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
}else if(c >= 0x000080 && c <= 0x0007FF){
bytes.push(((c >> 6) & 0x1F) | 0xC0);
bytes.push((c & 0x3F) | 0x80);
}else{
bytes.push(c & 0xFF);
}
}
return bytes;
}


具体为什么这么转,可以参考我的另一篇博客http://blog.csdn.net/a123638/article/details/46532385。

版权所有,嘿嘿!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息