JavaScript实现UTF-8编解码

 4282

JavaScript实现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实现代码,首先是编码

  1. function utf8Encode(inputStr) {
  2.     var outputStr = "";
  3.     for(var i = 0; i < inputStr.length; i++) {
  4.         var temp = inputStr.charCodeAt(i);
  5.         //0xxxxxxx
  6.         if(temp < 128) {
  7.             outputStr += String.fromCharCode(temp);
  8.         }
  9.         //110xxxxx 10xxxxxx
  10.         else if(temp < 2048) {
  11.             outputStr += String.fromCharCode((temp >> 6) | 192);
  12.             outputStr += String.fromCharCode((temp & 63) | 128);
  13.         }
  14.         //1110xxxx 10xxxxxx 10xxxxxx
  15.         else if(temp < 65536) {
  16.             outputStr += String.fromCharCode((temp >> 12) | 224);
  17.             outputStr += String.fromCharCode(((temp >> 6) & 63) | 128);
  18.             outputStr += String.fromCharCode((temp & 63) | 128);
  19.         }
  20.         //11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  21.         else {
  22.             outputStr += String.fromCharCode((temp >> 18) | 240);
  23.             outputStr += String.fromCharCode(((temp >> 12) & 63) | 128);
  24.             outputStr += String.fromCharCode(((temp >> 6) & 63) | 128);
  25.             outputStr += String.fromCharCode((temp & 63) | 128);
  26.         }
  27.     }
  28.     return outputStr;
  29. }

下面是解码

  1. function utf8Decode(inputStr) {
  2.     var outputStr = "";
  3.     var code1, code2, code3, code4;
  4.     for (var i = 0; i < inputStr.length; i++) {
  5.         code1 = inputStr.charCodeAt(i);
  6.         if (code1 < 128) {
  7.             outputStr += String.fromCharCode(code1);
  8.         } else if (code1 < 224) {
  9.             code2 = inputStr.charCodeAt(++i);
  10.             outputStr += String.fromCharCode(((code1 & 31) << 6) | (code2 & 63));
  11.         } else if (code1 < 240) {
  12.             code2 = inputStr.charCodeAt(++i);
  13.             code3 = inputStr.charCodeAt(++i);
  14.             outputStr += String.fromCharCode(((code1 & 15) << 12) | ((code2 & 63) << 6) | (code3 & 63));
  15.         } else {
  16.             code2 = inputStr.charCodeAt(++i);
  17.             code3 = inputStr.charCodeAt(++i);
  18.             code4 = inputStr.charCodeAt(++i);
  19.             outputStr += String.fromCharCode(((code1 & 7) << 18) | ((code2 & 63) << 12) |((code3 & 63) << 6) | (code2 & 63));
  20.         }
  21.     }
  22.     return outputStr;
  23. }

以上!



本文网址:https://www.zztuku.com/detail-8622.html
站长图库 - JavaScript实现UTF-8编解码
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐