UTF8是以8bits即1Bytes為編碼的最基本單位,當然也可以有基于16bits和32bits的形式,分別稱為UTF16和UTF32,但目前用得不多,而UTF8則被廣泛應用在文件儲存和網絡傳輸中。
編碼原理
先看這個模板:
UCS-4 range (hex.) UTF-8 octet sequence (binary)
0000 0000-0000 007F 0xxxxxxx
0000 0080-0000 07FF 110xxxxx 10xxxxxx
0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-001F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
0020 0000-03FF FFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
0400 0000-7FFF FFFF 1111110x 10xxxxxx ... 10xxxxxx
編碼步驟:
1) 首先確定需要多少個8bits(octets)
2) 按照上述模板填充每個octets的高位bits
3) 把字符的bits填充至x中,字符順序:低位→高位,UTF8順序:最后一個octet的最末位x→第一個octet最高位x
根據UTF8編碼,最多可由6個字節組成,所以UTF8是1-6字節編碼組成
C++代碼如下:
int IsTextUTF8(char* str,ULONGLONG length)
{
int i;
DWORD nBytes=0;//UFT8可用1-6個字節編碼,ASCII用一個字節
UCHAR chr;
BOOL bAllAscii=TRUE; //如果全部都是ASCII, 說明不是UTF-8
for(i=0;i<length;i++)
{
chr= *(str+i);
if( (chr&0x80) != 0 ) // 判斷是否ASCII編碼,如果不是,說明有可能是UTF-8,ASCII用7位編碼,但用一個字節存,最高位標記為0,o0xxxxxxx
bAllAscii= FALSE;
if(nBytes==0) //如果不是ASCII碼,應該是多字節符,計算字節數
{
if(chr>=0x80)
{
if(chr>=0xFC&&chr<=0xFD)
nBytes=6;
else if(chr>=0xF8)
nBytes=5;
else if(chr>=0xF0)
nBytes=4;
else if(chr>=0xE0)
nBytes=3;
else if(chr>=0xC0)
nBytes=2;
else
{
return FALSE;
}
nBytes--;
}
}
else //多字節符的非首字節,應為 10xxxxxx
{
if( (chr&0xC0) != 0x80 )
{
return FALSE;
}
nBytes--;
}
}
if( nBytes > 0 ) //違返規則
{
return FALSE;
}
if( bAllAscii ) //如果全部都是ASCII, 說明不是UTF-8
{
return FALSE;
}
return TRUE;
}