ARM Technical Support Knowledge Articles

LOGICAL NOT ('~') GIVES INCORRECT RESULTS

Applies to: General Topics

Answer


Information in this article applies to:


QUESTION

I 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?

ANSWER

ANSI 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 INFORMATION

Refer to the ANSI C Standard (ANSI/ISO 9899-1990), section 6.2.1.5 - Usual Arithmetic Conversions.

SEE ALSO

Article last edited on: 2002-12-04 00:00:00

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential