
首先簡單介紹一下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;
}以上!






