首先简单介绍一下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 < 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;}
相关免费学习推荐:javascript(视频)
以上就是学习使用javascript实现utf-8编解码的详细内容。