温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScrip如何t实现UTF-8编解码

发布时间:2021-01-25 09:14:06 来源:亿速云 阅读:223 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关JavaScrip如何t实现UTF-8编解码,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

首先简单介绍一下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的编码方式如下:

Unicode编码(十六进制)UTF-8 字节流(二进制)
000000-00007F0xxxxxxx
000080-0007FF110xxxxx 10xxxxxx
000800-00FFFF1110xxxx 10xxxxxx 10xxxxxx
010000-10FFFF11110xxx10xxxxxx10xxxxxx10xxxxxx

以下是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; }

关于“JavaScrip如何t实现UTF-8编解码”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI