float强制转换为相同。
使用WideCharToMultiByte
将UTF16转换为UTF8以发送到网络功能。
从网络功能接收UTF8时,使用MultiByteToWideChar
将其转换回UTF16,以便在Windows函数中使用。
示例:
#include <iostream>
#include <string>
#include <windows.h>
std::string get_utf8(const std::wstring &wstr)
{
if (wstr.empty()) return std::string();
int sz = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], -1, 0, 0, 0, 0);
std::string res(sz, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], -1, &res[0], sz, 0, 0);
return res;
}
std::wstring get_utf16(const std::string &str)
{
if (str.empty()) return std::wstring();
int sz = MultiByteToWideChar(CP_UTF8, 0, &str[0], -1, 0, 0);
std::wstring res(sz, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], -1, &res[0], sz);
return res;
}
int main()
{
std::wstring greek = L"ελληνικά";
std::string utf8 = get_utf8(greek);
std::wstring utf16 = get_utf16(utf8);
MessageBoxW(0, utf16.c_str(), 0, 0);
return 0;
}
编辑
以下示例将展示UTF16和UTF8之间的区别。该示例查看UTF16和UTF8的字节值。
请注意,对于拉丁字母表,UTF8和ANSI字节完全相同。
对于拉丁字母表,UTF8和UTF16有相似之处,但UTF16多了一个零。
对于希腊字母表和中文字符,差异明显。
void printbytes_char(const char* ANSI_or_UTF8)
{
const char *bytes = ANSI_or_UTF8;
int len = strlen(bytes);
for (size_t i = 0; i < len; i++)
printf("%02X ", 0xFF & bytes[i]);
printf("\n");
}
void printbytes_wchar_t(const wchar_t* UTF16)
{
const char *bytes = (const char*)UTF16;
int len = wcslen(UTF16) * 2;
for (size_t i = 0; i < len; i++)
printf("%02X ", 0xFF & bytes[i]);
printf("\n");
}
int main()
{
printbytes_char("ABC");
printbytes_char(u8"ABC");
printbytes_wchar_t(L"ABC");
printbytes_char(u8"ελληνικά");
printbytes_wchar_t(L"ελληνικά");
printbytes_char(u8"汉字/漢字");
printbytes_wchar_t(L"汉字/漢字");
return 0;
}
输出:
"ABC":
41 42 43 //ANSI
41 42 43 //UTF8
41 00 42 00 43 00 //UTF16 (this is little endian, bytes are swapped)
"ελληνικά"
CE B5 CE BB CE BB CE B7 CE BD CE B9 CE BA CE AC //UTF8
B5 03 BB 03 BB 03 B7 03 BD 03 B9 03 BA 03 AC 03 //UTF16
"汉字/漢字"
E6 B1 89 E5 AD 97 2F E6 BC A2 E5 AD 97 //UTF8
49 6C 57 5B 2F 00 22 6F 57 5B //UTF16
MultiByteToWideChar
和WideCharToMultiByte
进行 UTF16(Windows 标准)和 UTF8(网络友好)之间的转换。示例 - Barmak Shemiranistatic_cast
而不是C风格数组;它们可以防止这种混淆。 - asu