Wednesday, January 13, 2010

11.2.1 THE ONE'S COMPLEMENT OPERATOR

The one's complement operator (~) is a unary operator that causes the bits of its operand to be inverted (i.e., reversed) so that 1s become 0s and 0s become 1s. This operator always precedes its operands.The operand must be an integer-type quantity (including integer, long, short, unsigned, char, etc.).

Consider the simple C program shown below.


#include


main()
{
unsigned i = 0x5b3c;


printf("hexadecimal values: i = %x  ~i = %x\n", i, ~i);
printf("decimal equivalents: i = %u  ~i = %u\n", i, ~i);
}

Executing this program on a computer with a 16-bit word size results in the following output.


hexadecimal values: i = 5b3c    ~i = a4c3
decimal equivalents: i = 23356  ~i = 42179

To understand these results, first consider the bit patterns corresponding to the values for i and ~i.

i = 0101 1011 0011 1100
~i = 1010 0100 1100 0011

Therefore the decimal equivalents are

i= 23356 and ~i= 42179

No comments:

Post a Comment