使用JavaScript实现UTF-8编解码
来源:互联网 发布:淘宝虚拟现实购物 编辑:程序博客网 时间:2024/05/17 22:25
首先简单介绍一下UTF-8。UTF-8以字节为单位对Unicode进行编码。UTF-8的特点是对不同范围的字符使用不同长度的编码。对于0x00-0x7F之间的字符,UTF-8编码与ASCII编码完全相同。UTF-8编码的最大长度是6个字节。从上表可以看出,6字节模板有31个x,即可以容纳31位二进制数字。Unicode的最大码位0x7FFFFFFF也只有31位。
从Unicode到UTF-8的编码方式如下:
以下是js实现代码,首先是编码
function utf8Encode(inputStr) { var outputStr = ""; for(var i = 0; i < inputStr.length; i++) { var temp = inputStr.charCodeAt(i); //0xxxxxxx if(temp < 128) { outputStr += String.fromCharCode(temp); } //110xxxxx 10xxxxxx else if(temp < 2048) { outputStr += String.fromCharCode((temp >> 6) | 192); outputStr += String.fromCharCode((temp & 63) | 128); } //1110xxxx 10xxxxxx 10xxxxxx else if(temp < 65536) { outputStr += String.fromCharCode((temp >> 12) | 224); outputStr += String.fromCharCode(((temp >> 6) & 63) | 128); outputStr += String.fromCharCode((temp & 63) | 128); } //11110xxx 10xxxxxx 10xxxxxx 10xxxxxx else { outputStr += String.fromCharCode((temp >> 18) | 240); outputStr += String.fromCharCode(((temp >> 12) & 63) | 128); outputStr += String.fromCharCode(((temp >> 6) & 63) | 128); outputStr += String.fromCharCode((temp & 63) | 128); } } return outputStr;}
下面是解码
function utf8Decode(inputStr) { var outputStr = ""; var code1, code2, code3, code4; for(var i = 0; i < inputStr.length; i++) { code1 = inputStr.charCodeAt(i); if(code1 < 128) { outputStr += String.fromCharCode(code1); } else if(code1 < 224) { code2 = inputStr.charCodeAt(++i); outputStr += String.fromCharCode(((code1 & 31) << 6) | (code2 & 63)); } else if(code1 < 240) { code2 = inputStr.charCodeAt(++i); code3 = inputStr.charCodeAt(++i); outputStr += String.fromCharCode(((code1 & 15) << 12) | ((code2 & 63) << 6) | (code3 & 63)); } else { code2 = inputStr.charCodeAt(++i); code3 = inputStr.charCodeAt(++i); code4 = inputStr.charCodeAt(++i); outputStr += String.fromCharCode(((code1 & 7) << 18) | ((code2 & 63) << 12) |((code3 & 63) << 6) | (code2 & 63)); } } return outputStr;}
以上!
转载请注明原地址,谢谢!
阅读全文
0 0
- 使用JavaScript实现UTF-8编解码
- UTF-8编解码之实现
- UTF-8编解码之说明
- unicode utf-8 字符编解码
- JVM 字符编解码 UTF-8 UTF-16
- JavaScript 语言 Base64 编解码实现类
- VB URL的编解码源码 GB2312 UTF-8编解码
- 使用NDK实现的Base64编/解码
- 字符编解码的故事(ASCII,ANSI,Unicode,Utf-8)
- 用C++ 对中文进行UTF-8编解码
- javascript编解码
- javascript url 编码(UTF-8) jsp 解码
- Java 8实现BASE64编解码
- WCF编解码实现
- 使用Base64编解码
- 实现UTF-8、UCS2编码和解码
- 使用curl实现http传输,Url编解码问题
- 使用libaac(d)库实现PCM音频的编解码
- 六行代码安装 GPU版本的TensorFlow
- 高度注意 Map 类集合 K/V 能不能存储 null 值的情况
- 在阿里云ECS服务器上搭建tomcat
- php laraval框架 generate 生成key
- C++ auto和decltype浅析
- 使用JavaScript实现UTF-8编解码
- [HDU] 1754
- NKOI Round 8(12.14)
- Core Animation 之CAAnimation
- NESS漏洞扫描SSH WeakAlgorithms Supported漏洞的解决
- 1143: 最大值—多种进制
- numpy数据类型
- Eclipse在线安装黑色主题(DarkTheme)
- 神经网络为什么要归一化?