免费学习推荐:javascript视频教程
首先简单介绍一下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-00007F | 0xxxxxxx |
000080-0007FF | 110xxxxx 10xxxxxx |
000800-00FFFF | 1110xxxx 10xxxxxx 10xxxxxx |
010000-10FFFF | 11110xxx10xxxxxx10xxxxxx10xxxxxx |
以下是js实现代码,首先是编码
function utf8Encode(inputStr) { var outputStr = ""; for(var i = 0; i > 6) | 192); outputStr += String.fromCharCode((temp & 63) | 128); } //1110xxxx 10xxxxxx 10xxxxxx else if(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 <p>以上!</p><blockquote><p><strong>相关免费学习推荐:</strong><a href="https://www.php.cn/course/list/17.html" target="_blank" textvalue="javascript"><strong>javascript</strong></a><strong>(视频)</strong></p></blockquote>
以上就是JavaScript实现UTF-8编解码的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号