Using the == operator to compare char with 0x80 always results in an error?

char byte = 0x80 if(byte == 0x80) { cout << "This message never gets printed!"; } 

The hexadecimal value 0x80 equivalent in binary format to 1000 0000 , which clearly corresponds to the byte.

However, the compiler warns me of a conditional line:

 warning: comparison is always false due to limited range of data type 

Why is the result of conditional false in this case?

Is 0x80 a conditional extension to something like 0x80000000 ?

Is it possible to use the == operator to check if char 0x80 ?

+1
source share
2 answers

The problem is that char in the C and C ++ standards determines that it can be either a signed or unsigned value, and must contain at least 8 bits. It appears that the architecture and the compiler use signed 8-bit char values.

This means that any value with the highest bit (bit 7) will be negative. Thus, 0x80 as char becomes -128 decimal.

The constant 0x80 is not a char value, it is an int value.

So, when you compare -128 with 0x80 (128), they do not match and can never be, and the compiler understands this and issues a warning.

There are many ways to achieve this, here are a few possible scenarios:

First, we can use any value for another:

 if (((int)byte) & 0xff == 0x80) 

or

 if (byte == (char)0x80) 

Alternatively, we can make the constant a char value, not an int value.

 if (byte == '\200') // Octal 200 = 0x80. 

or

 if (byte == '\x80') 

Alternatively use unsigned char byte = 0x80; - indicating that it is unsigned char guarantees that it does not flip to negative.

+6
source

The signed char type can contain values 0x7f to -0x80 for a total of 256 values. The unsigned char type may contain the value 0x80 , since the maximum value is 0xff . Apparently, the implementation of the char type you are using is the signed char type.

Assigning 0x80 a signed char forces the value to overflow, making the value -0x80 . The signed char type cannot represent 0x80 for the system, as it is always interpreted as -0x80 . This is because the most significant bit is used as a sign bit.

Your comparison may be successful if you used bitwise and: byte & 0x80 . Note that the result of this operation does not mean equality in either direction, just whether the most significant bit is set.

0
source

All Articles