Unicode主要是為多語(yǔ)言設(shè)立的二進(jìn)制編碼,一個(gè)字符的Unicode編碼是確定的。但是在實(shí)際傳輸過(guò)程中,由于不同系統(tǒng)平臺(tái)的設(shè)計(jì)不一定一致,以及出于節(jié)省空間的目的,對(duì) Unicode 編碼的實(shí)現(xiàn)方式有所不同。Unicode 的實(shí)現(xiàn)方式稱(chēng)為Unicode轉(zhuǎn)換格式(Unicode Translation Format,簡(jiǎn)稱(chēng)為
UTF)。UTF-8 編碼,是變長(zhǎng)編碼,它將基本7位ASCII字符仍用7位編碼表示,占用一個(gè)字節(jié)(首位補(bǔ)0)。而遇到與其他 Unicode 字符混合的情況,將按一定算法轉(zhuǎn)換,每個(gè)字符使用1-3個(gè)字節(jié)編碼,并利用首位為0或1進(jìn)行識(shí)別。
UTF-8其實(shí)只是Unicode的一個(gè)子集,在WM5.0中實(shí)現(xiàn)Unicode到UTF-8的轉(zhuǎn)換,不必用位運(yùn)算就可以。代碼如下:
/////////////////////////////////////////////////////////////////////////////
//Description:
// This function maps a wide-character string to a new character string
//
//Parameters:
// lpcwszStr: [in] Pointer to the character string to be converted
// lpszStr: [out] Pointer to a buffer that receives the translated string.
// dwSize: [in] Size of the buffer
//
//Return Values:
// TRUE: Succeed
// FALSE: Failed
//
//Example:
// MByteToWChar(szW,szA,sizeof(szA)/sizeof(szA[0]));
//////////////////////////////////////////////////////////////////////////////
BOOL WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize)
{
DWORD dwMinSize;
dwMinSize = WideCharToMultiByte(CP_UTF8,NULL,lpcwszStr,-1,NULL,0,NULL,FALSE);
if(dwSize < dwMinSize)
{
return FALSE;
}
WideCharToMultiByte(CP_UTF8,NULL,lpcwszStr,-1,lpszStr,dwSize,NULL,FALSE);
return TRUE;
}
參數(shù)LPCSTR lpszStr就是個(gè)UTF-8字符串。