Clarification by bitwise operator (~) required

Suppose you have the following C code.

unsigned char a = 1; printf("%d\n", ~a); // prints -2 printf("%d\n", a); // prints 1 

I am surprised to see -2 printed as a result of ~ 1 conversion:

The opposite is 0000 0001 - 1111 1110. This is nothing but -2. A.

What am I missing here?

+4
source share
3 answers

These are two additions.

In two additional representations, if the number x of the most significant bits is 1, then the actual value will be & minus; (~ x + 1).

For instance,

 0b11110000 = -(~0b1111 + 1) = -(15 + 1) = -16. 

This is a natural representation of negative numbers since

 0000001 = 1 0000000 = 0 1111111 = -1 (wrap around) 1111110 = -2 1111101 = -3 etc. 

See http://en.wikipedia.org/wiki/Two%27s_complement for more details.


BTW, to print an unsigned value, use the %hhu or %hhx . See http://www.ideone.com/YafE3 .

+10
source

% d stands for signed decimal, not unsigned. Thus, your bit pattern, even if it is stored in an unsigned variable, is interpreted as a signed number.

See the Wikipedia entry for signed numbers for an understanding of bit values. In particular, see Two Additions .

+4
source

One (slightly humorous) way of thinking about signed mathematicians is to admit that the most significant bit does represent an infinite number of bits above it. Thus, in a 16-bit signed number, the most significant bit is 32768 + 65536 + 131072 + 262144 + ... etc. which is 32768 * (1 + 2 + 4 + 8 + ...) Using the standard formula for the power series, (1 + X + X ^ 2 + X ^ 3 + ...) = 1 / (1-X), it turns out that (1 + 2 + 4 + 8 + ...) is -1, so the sum of all these bits is -32768.

0
source

All Articles