使用==运算符将char与0x80进行比较始终会导致错误? [英] Using the == operator to compare a char to 0x80 always results in 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
?
推荐答案
问题是,在C和C ++标准中,char
定义为可以为有符号或无符号值,并且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)的值都将为负值.因此,作为char
的0x80变为-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;
-指定它是一个无符号字符,将确保它不会翻转为负数".
Alternatively, use an unsigned char byte = 0x80;
- specifying that it's an unsigned char will ensure that it doesn't "flip to negative".
这篇关于使用==运算符将char与0x80进行比较始终会导致错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!