UTF8转码

 1 inline void WStrToUTF8(std::string& dest, const wstring& src){
 2 
 3 dest.clear();
 4 
 5 for (size_t i = 0; i < src.size(); i++){
 6 
 7 wchar_t w = src[i];
 8 
 9 if (w <= 0x7f)
10 
11 dest.push_back((char)w);
12 
13 else if (w <= 0x7ff){
14 
15 dest.push_back(0xc0 | ((w >> 6)& 0x1f));
16 
17 dest.push_back(0x80| (w & 0x3f));
18 
19 }
20 
21 else if (w <= 0xffff){
22 
23 dest.push_back(0xe0 | ((w >> 12)& 0x0f));
24 
25 dest.push_back(0x80| ((w >> 6) & 0x3f));
26 
27 dest.push_back(0x80| (w & 0x3f));
28 
29 }
30 
31 else if (sizeof(wchar_t) > 2 && w <= 0x10ffff){
32 
33 dest.push_back(0xf0 | ((w >> 18)& 0x07)); // wchar_t 4-bytes situation
34 
35 dest.push_back(0x80| ((w >> 12) & 0x3f));
36 
37 dest.push_back(0x80| ((w >> 6) & 0x3f));
38 
39 dest.push_back(0x80| (w & 0x3f));
40 
41 }
42 
43 else
44 
45 dest.push_back('?');
46 
47 }
48 
49 }
50 
51 //! simple warpper
52 
53 inline std::string WStrToUTF8(const std::wstring& str){
54 
55 std::string result;
56 
57 WStrToUTF8(result, str);
58 
59 return result;
60 
61 }

 

posted @ 2014-04-10 17:46  无语男  阅读(183)  评论(0)    收藏  举报