Win32字串編碼格式轉化

2021-07-15 20:31:03 字數 1885 閱讀 5623

1.ascii轉unicode

wstring asciitounicode(string asciistr)

std::vectorresultstring(widesize);

int count = multibytetowidechar(cp_acp, 0, (char*)asciistr.c_str(), -1, &resultstring[0], widesize);

if(0 == count)

return std::wstring(&resultstring[0]);

}

2.utf8轉unicode

std::wstring utf8tounicode(const std::string &s)

// compute the length of the buffer we'll need

int charcount = multibytetowidechar(cp_utf8, 0, s.c_str(), -1, null, 0);

if (charcount == 0)

// convert

wchar_t* buf = new wchar_t[charcount];

multibytetowidechar(cp_utf8, 0, s.c_str(), -1, buf, charcount);

wstring result(buf);

delete buf;

return result;

}

3.unicode 轉ascii

string  unicodetoascii(wstring unicodestr)

// convert

char *buf = new char[charcount];

widechartomultibyte(cp_acp, 0, unicodestr.c_str(), -1, buf, charcount,

null, null);

string result(buf);

delete buf;

return result;

}

4.unicode轉utf8

string  unicodetoutf8(wstring unicodestr)

std::vectorresultstr(utf8size);

int count = ::widechartomultibyte(cp_utf8, 0, unicodestr.c_str(), -1, &resultstr[0], utf8size, null, null);

if(0 == count)

return std::string(&resultstr[0]);

}

5.ascii轉utf8

string publicfunction::asictoutf8(string asic)

6.utf8轉ascii

string utf8toasic(string utf8)

總結:轉編碼格式轉化的時候,如果轉化的雙方不是unicode編碼,那麼一定要通過unicode做中轉,也就是說一定要先轉化成unicode,然後再轉化成目標編碼。

轉化時怎樣決定編碼(使用cp_utf8還是cp_acp),只要是轉unicode,那麼如果是utf8轉unicode(或者unicode轉utf8),那麼肯定用cp_utf8;

如果是ascii轉unicode(或者unicode轉ascii),那麼肯定用cp_acp。

C 字串型別說明 Win32 字元編碼

引言 毫無疑問,我們都看到過像 tchar,std string,bstr 等各種各樣的字串型別,還有那些以 tcs 開頭的奇怪的巨集。你也許正在盯著顯示器發愁。本指引將總結引進各種字元型別的目的,展示一些簡單的用法,並告訴您在必要時,如何實現各種字串型別之間的轉換。在第一部分,我們將介紹3種字元編...

C 字串完全指南 Win32字元編碼(一)

c 字串完全指南 win32字元編碼 一 前言 字串的表現形式各異,象tchar,std string,bstr等等,有時還會見到怪怪的用 tcs起頭的巨集。這個指南的目的就是說明各種字串型別及其用途,並說明如何在必要時進行型別的相互轉換。在指南的第一部分,介紹三種字元編碼格式。理解編碼的工作原理是...

C 字串完全指南 Win32字元編碼(一)

c 字串完全指南 win32字元編碼 一 2002 11 14 17 38 53 前言 字串的表現形式各異,象tchar,std string,bstr等等,有時還會見到怪怪的用 tcs起頭的巨集。這個指南的目的就是說明各種字串型別及其用途,並說明如何在必要時進行型別的相互轉換。在指南的第一部分,介...