我想打印单词“?esnek”的单个字节,期望打印 7 个字节,因为“?” 以 2 个字节编码,但它会在终端中打印垃圾字符,例如问号。如果我打印出整数值,我会得到这个序列。
-60 -115 101 115 110 101 107
Run Code Online (Sandbox Code Playgroud)
为什么前两个数字是负数?这是我用来尝试的代码。
char *utfstring = "?esnek";
for(size_t i = 0; i < strlen(utfstring); i++) {
printf("%c ", utfstring[i]);
}
for(size_t i = 0; i < strlen(utfstring); i++) {
printf("%d ", utfstring[i]);
}
Run Code Online (Sandbox Code Playgroud)
我预计前两个值是 c4 8d 因为?根据https://www.utf8-chartable.de/unicode-utf8-table.pl?start=256&unicodeinhtml=dec 进行编码
Use (unsigned char)utfstring[i]
or 0xFF & utfstring[i]
to get hexadecimal output as follows:
char *utfstring = u8"?esnek";
for(size_t i = 0; i < strlen(utfstring); i++)
printf("%02X ", 0xFF & utfstring[i]);
Run Code Online (Sandbox Code Playgroud)
output:
"C4 8D 65 73 6E 65 6B"
Run Code Online (Sandbox Code Playgroud)
The first alphabetic character ?
cannot be represented by a single byte in UTF8. If you print utfstring
one byte at a time, then the UTF8 encoding is broken.
It has to be printed as u8"?"
or u8"\xC4\x8D"
通常,如果您希望将字节序列分解为单独的 Unicode 代码点,则需要一个 Unicode 库,例如 iconv。如果您只是想查找?
,则使用标准字符串函数,例如strstr(utfstring, u8"?")
。
归档时间: |
|
查看次数: |
4614 次 |
最近记录: |