一、簡單明瞭的說下這些區別和關係,網上說的太繁瑣、或者太單一。
寬字節:通常用兩個字節表示一個字符,對應的就是Unicode。
多字節:用多個字節表示一個字符,對應的就是ANSI。
ANSI:他的產生源於ASCII字符集,最開始7個bits,總共代表了128個字符,包括英文、字母、數字、和一些特殊字符。後面由於各個國家爲了彰顯自己的本土語音,進行了擴充,產生了 GB2312, BIG5, JIS等編碼,形成了ANSI編碼,現在可以看到一些把和ASCII和GBK混合在一起說就是這個原因。
Unicode:他的產生是爲了統一不同國家的字符編碼,不同的語言無法存儲在同一段 ANSI 編碼的文本中,因此中間橋樑Unicode出現了,Unicode把所有語言都統一到一套編碼裏,因此就不要出現亂碼情況。因此他又有另一個名字:萬國碼。
GBK:它是之前提到的由ANSI產生的GB2312的一個擴充,相當於增強版,收錄了更過的漢字字符。
二、ANSI與UTF-8之間的轉換。
(1)直接在VS上面複製粘貼即可運行
#include<stdio.h>
#include<windows.h>
#define CODE_LEN 256
void AnsiToUtf8(char* lpcszStr, char* lpwszStr)
{
WCHAR* strA;
int i = MultiByteToWideChar(CP_ACP, 0, lpcszStr, -1, NULL, 0);
strA = new WCHAR[i];
MultiByteToWideChar(CP_ACP, 0, lpcszStr, -1, strA, i);
i = WideCharToMultiByte(CP_UTF8, 0, strA, -1, NULL, 0, NULL, NULL);
char* strB = new char[i];
WideCharToMultiByte(CP_UTF8, 0, strA, -1, lpwszStr, i, NULL, NULL);
}
void Utf8ToAnsi(char* lpcszStr, char* lpwszStr)
{
DWORD dwMinSize;
WCHAR* strTmp;
dwMinSize = MultiByteToWideChar(CP_UTF8, 0, lpcszStr, -1, NULL, 0);
strTmp = new WCHAR[dwMinSize];
MultiByteToWideChar(CP_UTF8, 0, lpcszStr, -1, strTmp, dwMinSize);
int targetLen = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)strTmp, -1, (char*)lpwszStr, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, (LPWSTR)strTmp, -1, (char*)lpwszStr, targetLen, NULL, NULL);
}
int main()
{
char str1_src[CODE_LEN] = "測試";
char str2_des[CODE_LEN] = { 0 };
char str3_src[CODE_LEN] = "嫺嬭瘯";
char str4_des[CODE_LEN] = { 0 };
AnsiToUtf8(str1_src, str2_des);
printf("測試的ANSI轉換成utf-8爲:%s----->%s\n\n",str1_src, str2_des);
Utf8ToAnsi(str3_src, str4_des);
printf("測試的utf-8轉換成ANSI爲:%s----->%s",str3_src, str4_des);
return 0;
}
(2)運行結果
(3)注意:假如在VC6.0上面運行創建的不使用C++風格那麼需要注意裏面使用到的new運算符,此時只需要使用malloc就可以。