WM5.0下,Unicode轉(zhuǎn)UTF-8的方法
Unicode主要是為多語言設(shè)立的二進(jìn)制編碼,一個字符的Unicode編碼是確定的。但是在實(shí)際傳輸過程中,由于不同系統(tǒng)平臺的設(shè)計不一定一致,以及出于節(jié)省空間的目的,對 Unicode 編碼的實(shí)現(xiàn)方式有所不同。Unicode 的實(shí)現(xiàn)方式稱為Unicode轉(zhuǎn)換格式(Unicode Translation Format,簡稱為 UTF)。UTF-8 編碼,是變長編碼,它將基本7位ASCII字符仍用7位編碼表示,占用一個字節(jié)(首位補(bǔ)0)。而遇到與其他 Unicode 字符混合的情況,將按一定算法轉(zhuǎn)換,每個字符使用1-3個字節(jié)編碼,并利用首位為0或1進(jìn)行識別。
UTF-8其實(shí)只是Unicode的一個子集,在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就是個UTF-8字符串。
UTF-8其實(shí)只是Unicode的一個子集,在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就是個UTF-8字符串。
posted on 2008-11-02 21:46 Benjamin 閱讀(798) 評論(0) 編輯 收藏 引用 所屬分類: PDA/PPC開發(fā)

