介绍
小编给大家分享一下使用JavaScript实现utf - 8编解码的方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!
首先简单介绍一下utf - 8. - utf - 8以字节为单位对Unicode进行编码。 utf - 8的特点是对不同范围的字符使用不同长度的编码。 对于0 x00-0x7f之间的字符,utf - 8编码与ASCII编码完全相同.UTF-8编码的最大长度是6个字节。 6字节模板有31个x,即可以容纳31位二进制数字.Unicode的最大码位0 x7fffffff也只有31位。
从Unicode到utf - 8的编码方式如下:
Unicode编码(十六进制)utf - 8字节流(二进制)000000 - 00007 - f0xxxxxxx000080 10 - 0007 ff110xxxxx xxxxxx000800-00ffff1110xxxx 10 xxxxxx xxxxxx010000-10ffff11110xxx10xxxxxx10xxxxxx10xxxxxx以下是js实现代码,首先是编码
function utf8Encode (inputStr), { var 才能;outputStr =,““ ,, ,,(var 小姐:=,0;,小姐:& lt;, inputStr.length;,我+ +),{ ,,,var temp =, inputStr.charCodeAt(我); ,,,, ,,,//0 xxxxxxx ,,,如果(temp & lt;, 128), { ,,,,,outputStr +=, String.fromCharCode(临时); ,,,} ,,,//110 xxxxx 10 xxxxxx ,,,else 如果(temp & lt;, 2048), { ,,,,,outputStr +=, String.fromCharCode ((, temp 的在祝辞,6),|,192); ,,,,,outputStr +=, String.fromCharCode ((temp ,, 63), |, 128); ,,,} ,,,//1110 xxxx 10 xxxxxx 10 xxxxxx ,,,else 如果(temp & lt;, 65536), { ,,,,,outputStr +=, String.fromCharCode ((, temp 的在祝辞,12),|,224); ,,,,,outputStr +=, String.fromCharCode (((, temp 的在祝辞,6),,,63),|,128); ,,,,,outputStr +=, String.fromCharCode ((temp ,, 63), |, 128); ,,,} ,,,//11110 xxx 10 xxxxxx 10 xxxxxx 10 xxxxxx ,,,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; ,, ,,(var 小姐:=,0;,小姐:& lt;, inputStr.length;,我+ +),{ ,,,code1 =, inputStr.charCodeAt(我); ,,,, ,,,如果(code1 & lt;, 128), { ,,,,,outputStr +=, String.fromCharCode (code1); ,,,} ,,,else 如果(code1 & lt;, 224), { ,,,,,code2 =, inputStr.charCodeAt (+ + i); ,,,,,outputStr +=, String.fromCharCode (((, code1 31), & lt; & lt;, 6), |, (code2 ,, 63)); ,,,} ,,,else 如果(code1 & lt;, 240), { ,,,,,code2 =, inputStr.charCodeAt (+ + i); ,,,,,code3 =, inputStr.charCodeAt (+ + i); ,,,,,outputStr +=, String.fromCharCode (((, code1 15), & lt; & lt;, 12), |, ((code2 ,, 63), & lt; & lt;, 6), |, (code3 ,, 63)); ,,,} ,,,else { ,,,,,code2 =, inputStr.charCodeAt (+ + i); ,,,,,code3 =, inputStr.charCodeAt (+ + i); ,,,,,code4 =, inputStr.charCodeAt (+ + i); ,,,,,outputStr +=, String.fromCharCode (((, code1 7), & lt; & lt;, 18), |, ((code2 ,, 63), & lt; & lt;, 12), | ((code3 ,, 63), & lt; & lt;, 6), |, (code2 ,, 63)); ,,,} ,,} ,, return 才能;outputStr; }
以上是“使用JavaScript实现utf - 8编解码的方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!