C++ 中奇怪的 char 行为/ MSVC2005 / Windows 7 64位
我正在使用带有 MSVC2005 和 QT 的 Windows 7 64 位(但我怀疑 QT 导致了这个问题,因为这是基本数据类型 char 的问题。
所以当我尝试比较两个 char 时
char A=0xAA;
if(A==0xAA)
printf("Success");
else
printf("Fail");
,瞧,它失败了!但是当我这样做
char A=0xAA;
char B=0xAA;
if(A==B)
printf("Success");
else
printf("Fail");
我成功了!实际上,当我想到这一点时...嘿,我正在使用 64 位处理器..即使 char 应该被视为 1 个字节,但它可能会存储为 4 个字节。 所以
char A=0xAA;
if(A==0xFFFFFFAA)
printf("Success");
else
printf("Fail");
现在我成功了!!!
但是WTF!这是标准行为吗!!如果该死的东西被定义为 char,编译器不应该知道如何处理它吗?进一步的测试表明,如果字符的最高有效位是 1,则额外的字节仅存储为 1。因此 0x07 及更低的字节存储为 0x00000007。 WTF。
事实上,我似乎已经回答了我所有的问题......除了打电话给谁来修复这个错误。这还是一个错误吗?您可以在 64 位操作系统上使用 MSVC2005,否则我是个白痴。我想我应该让 qt Creator 使用 MSVC2010..该死。我的2个小时就这样过去了。
I am using windows 7 64 bit with MSVC2005 and QT (but I doubt QT is causing the problem since this is an issue with the fundamental data type char.
So when I try to compare two char's like so
char A=0xAA;
if(A==0xAA)
printf("Success");
else
printf("Fail");
lo and behold it fails! but when I do this
char A=0xAA;
char B=0xAA;
if(A==B)
printf("Success");
else
printf("Fail");
I get success! Actually when I thought about it... hey I'm working on a 64 bit processor.. even though char's are supposed to be treated as 1 byte. It's probablly stored as 4 bytes.
So
char A=0xAA;
if(A==0xFFFFFFAA)
printf("Success");
else
printf("Fail");
Now I get success!!!
But WTF! Is this standard behavior!! If the damn thing is defined as a char, shouldn't the compiler know what to do with it? Further tests show that the extra bytes are only stored as one's if the most significant bit of the char is a 1. So 0x07 and lower is stored as 0x00000007. WTF.
Actually I seemed to have answered all my questions... except who to call to get this bug fixed. Is this even a bug? You can use MSVC2005 on 64 bit operating systems right or am I being an idiot. I guess I should get qt creator to use MSVC2010.. damn it. There goes my 2 hours.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在将值为 -86 (256-0xAA) 的(有符号)字符与值为 170 (0xAA) 的整数进行比较。
同样的情况也会发生在 32 位系统和 8 位系统上。
You are comparing a (signed) char with the value -86 (256-0xAA) to an integer with the value 170 (0xAA).
The same will happen on a 32-bit system, and an 8-bit system, for that matter.
与 64 位无关:您需要将 A 定义为 unsigned char 才能获得正确的行为。编译器警告显示此代码可能不正确:
warning C4309: 'initializing' : truncation of Constant value
Not related to 64 bit: you need to define A as unsigned char to get correct behavior. Compiler warning shows that this code may be incorrect:
warning C4309: 'initializing' : truncation of constant value