使用 == 运算符将 char 与 0x80 进行比较总是会导致 false?
char byte = 0x80
if(byte == 0x80)
{
cout << "This message never gets printed!";
}
十六进制值0x80
在二进制中相当于1000 0000
,显然适合一个字节.
The hexadecimal value 0x80
is equivalent in binary to 1000 0000
, which clearly fits in a byte.
但是,编译器会警告我带有条件的行:
However, the compiler warns me about the line with the conditional:
warning: comparison is always false due to limited range of data type
为什么在这种情况下条件为假的结果?
Why is the result of the conditional false in this case?
0x80
是否在条件中扩展为 0x80000000
之类的内容?
Is 0x80
getting expanded in the conditional to something like 0x80000000
?
是否可以使用 ==
运算符来检查 char
是否等于 0x80
?
Is it possible to use the ==
operator to check if a char
equals 0x80
?
推荐答案
问题是 char
在 C 和 C++ 标准中定义它可以是有符号或无符号值,并且 char
必须至少有 8 位.有问题的体系结构和编译器似乎使用带符号的 8 位 char
值.
The problem is that char
is, in the C and C++ standards, defined that it can be either a signed or an unsigned value, and that a char
must have at least 8 bits. The architecture and compiler in question appears to use signed 8-bit char
values.
这意味着任何最高位(第 7 位)的值都是负值.所以 0x80 作为 char
变成 -128 十进制.
This means that any value with the highest bit (bit 7) will be a negative value. So 0x80 as a char
becomes -128 decimal.
常量 0x80 不是 char
值,它是 int
值.
The constant 0x80 is not a char
value, it is an int
value.
因此,当您将 -128 与 0x80 (128) 进行比较时,它们并不相同,而且永远不可能相同,编译器会发现这一点并发出警告.
So when you compare -128 with 0x80 (128) they are not the same, and can never be, and the compiler figures this out and issues a warning.
有多种方法可以实现这一点,这里有几种可能的场景:
There are a variety of ways to achieve this, here are a few possible scenarios:
首先,我们可以将其中一个值转换为另一个值的类型:
First, we can cast either value to the type of the other:
if (((int)byte) & 0xff == 0x80)
或
if (byte == (char)0x80)
或者,我们可以将常量变成 char
值,而不是 int
值.
Alternatively, we can make the constant into a char
value, rather than an int
value.
if (byte == '200') // Octal 200 = 0x80.
或
if (byte == 'x80')
或者,使用 unsigned char byte = 0x80;
- 指定它是 unsigned char 将确保它不会翻转为负数".
Alternatively, use an unsigned char byte = 0x80;
- specifying that it's an unsigned char will ensure that it doesn't "flip to negative".
相关文章