Using the == operator to compare a char to 0x80 always results in false?(使用 == 运算符将 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".
这篇关于使用 == 运算符将 char 与 0x80 进行比较总是会导致 false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 == 运算符将 char 与 0x80 进行比较总是会导致 false?
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
