javascript中string转UTF8格式byte数组
2015-06-17 16:29
591 查看
在javascript代码中,有些地方我们需要将string转为byte数组再进行进一步处理,网上太少这方面的资料。这里我根据java中String.getByte(“UTF-8”)的实现机制来进行string转byte数组的处理,同时解决中文和非英文字母转byte数组时的编码问题。其代码如下:
经过算法可精简为以下代码:
具体为什么这么转,可以参考我的另一篇博客http://blog.csdn.net/a123638/article/details/46532385。
版权所有,嘿嘿!
/** *@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。
版权所有,嘿嘿!
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- Extjs4.0 最新最全视频教程
- Javascript中toFixed方法的改进
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 5个常见可用性错误和解决方案
- String.intern
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 异步流程控制:7 行代码学会 co 模块
- JavaScript拆分字符串时产生空字符的原因
- IE8开发人员工具教程(二)
- Prototype源码浅析 String部分(二)