如何将Unicode
(例如字符向上箭头)分配给wchar_t
变量?
答案 0 :(得分:0)
wchar_t
可能是32位,但在Windows 16位上,UTF-16LE编码,有时需要两个wchar_t来存储一个Unicode代码点。
UTF-16LE和UTF-16BE不是线性的,具有可能不会分成两个字符串的对。并且wchar_t是不可移植的。
因此最好使用UTF-8和char
。
void append_utf8(string& s, uint cp) {
if (cp < 0x80 && cp != 0) {
// Let encode U+0 too (Modified UTF-8), as non-terminator?
s.append(1, (char) cp);
} else {
char cpBytes[6];
int bi = 0;
int lastPrefix = 0xC0;
int lastMask = 0x1F;
for (;;) {
int b = 0x80 | (cp & 0x3F);
cpBytes[bi] = (char)b;
++bi;
cp >>= 6;
if ((cp & ~lastMask) == 0) {
cpBytes[bi] = (char) (lastPrefix | cp);
++bi;
break;
}
lastPrefix = 0x80 | (lastPrefix >> 1);
lastMask >>= 1;
}
while (bi > 0) {
--bi;
s.append(1, cpBytes[bi]);
}
}
}
string s;
append_utf8(s, 0x2191): // For U+2191 up arrow.
append_utf8(s, 0x1F913): // For U+01F913 emoji nerd face.
对于Windows上的宽字符(UTF-16),例如:
void append_wch(std::wstring& s, uint cp) {
if (cp < 0x10000) {
s.append(1, (wchar_t) cp);
} else {
cp -= 0x10000;
uint w = (cp >> 6) + 0xD800;
s.append(1, (wchar_t) w);
w = (cp & 0x3FF) + 0xDC00;
s.append(1, (wchar_t) w);
}
}
(介意我受到Java影响。)