C/C++ Unicode字符编码大小和默认格式

Mar*_* A. 2 c++ unicode character-encoding multibyte visual-studio-2012

我刚刚意识到(感谢我的大学课程)我认为我知道unicode的许多事情都是错的.因此,我开始阅读并修复我的知识,并立即通过在MSVC2012中使用简单的"Hello world"C++程序来产生以下疑问:

#include <iostream>
#include <string.h>
using namespace std;

int main(void) {

    char arr1[] = "I am a nice boy"; // Is this stored as UTF-8 (multi-byte) or ASCII?
    char arr[] = "I'm a nice èboi"; // All characters should be ASCII except the 'è' one, which encoding is used for this?
    cout << strlen(arr); // Returns 15 as ASCII, why?

    // If I choose "multi-byte character set" in my VS project configuration instead of "unicode", what does this mean and what
    // will this affect?

    char arr2[] = "I'm a niße boy"; // And what encoding is it used here?
    cout << strlen(arr2); // Returns 1514, what does this mean?

    // If UTF-32 usually use 4 bytes to encode a character (even if they're not needed), how can a unicode code point like U+FFFF
    // (FFFF hexadecimal is 65535 in decimal) represent any possible unicode character if the maximum is FFFF ? (http://inamidst.com/stuff/unidata/)

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面是用"多字节字符集"编译的,但由于多字节是一种unicode编码,我猜(?)即使这个也不清楚.

有人可以帮助我解决上述问题的明确解释吗?

bam*_*s53 6

    char arr1[] = "I am a nice boy"; // Is this stored as UTF-8 (multi-byte) or ASCII?
Run Code Online (Sandbox Code Playgroud)

它存储在编译器的执行字符集中.编译器可以选择它是什么并且应该记录它.GCC允许您使用标志设置执行编码,-fexec-charset=charset但我认为默认情况下使用UTF-8,MSVC使用系统语言设置中配置的机器的"非Unicode应用程序编码"(永远不能是UTF-8)和clang无条件使用UTF-8.

char arr[] = "I'm a nice èboi"; // All characters should be ASCII except the 'è' one, which encoding is used for this?
cout << strlen(arr); // Returns 15 as ASCII, why?
Run Code Online (Sandbox Code Playgroud)

编译器执行字符集实际上根本不必与ASCII兼容.例如,它可能是EBDIC.

strlen(arr)返回15,因为使用编译器执行字符集编码的字符串文字长度为15个字节.由于字符串文字长度为15个字符,这可能意味着编译器执行字符集为每个字符使用了一个字节,包括"è".(并且因为UTF-8不能仅在15个字节中编码该字符串,这最终表明您的编译器没有使用UTF-8作为编译器执行字符集.)

char arr2[] = "I'm a niße boy"; // And what encoding is it used here?
cout << strlen(arr2); // Returns 1514, what does this mean?
Run Code Online (Sandbox Code Playgroud)

编码不会根据字符串的内容而改变.编译器将始终使用执行字符集.我假设'1514'是一个拼写错误,strlen(arr2)实际上返回14,因为该字符串中有14个字符,因为早期的字符串似乎也使用每个字符一个字节.

如果我在VS项目配置中选择"多字节字符集"而不是"unicode",这意味着什么,这会产生什么影响?

该设置与编译器使用的编码无关.它只是将Microsoft标题中的宏设置为不同的东西.TCHAR,所有在*W和*A函数之间选择的宏等.

实际上,当你启用'unicode'时,完全有可能使用多字节字符串编写程序,当你启用'多字节字符集'时,也可以使用unicode.

如果UTF-32通常使用4个字节来编码一个字符(即使它们不需要),如果最大值为FFFF,如何将U + FFFF(十进制FFFF十六进制为65535)的unicode代码点表示任何可能的unicode字符. ?(http://inamidst.com/stuff/unidata/)

这个问题毫无意义.也许如果你改写......