| |||||
Technical Support Support Resources
Product Information | GENERAL: LOGICAL NOT ('~') GIVES INCORRECT RESULTSInformation in this article applies to:
QUESTIONI get strange results when I compare character values. This is shown in the following example:
unsigned char a = 0x7F;
if (a == ~0x80) { // ~0x80 should match 0x7F
a = 0; // and therefore a should be set to zero
}
The comparison fails. Why? Isn't ~0x80 identical to 0x7F? ANSWERANSI C requires that expression values are promoted to integer data types unless otherwise specified. Therefore, the value of the expression ~0x80 is 0xFF7F (since an int is 16-bits). To get the results you expect, you must explicitly cast the value as follows:
unsigned char a = 0x7F;
if (a == ((unsigned char) ~0x80)) { // gives 0x7F
a = 0; // and the test is OK.
}
MORE INFORMATIONRefer to the ANSI C Standard (ANSI/ISO 9899-1990), section 6.2.1.5 - Usual Arithmetic Conversions. SEE ALSOLast Reviewed: Wednesday, December 04, 2002 | ||||
| |||||