<ra********@yahoo.com> wrote
I am not clear what is the difference between signed and unsigned
in C. Many say, unsigned means only +ve values and 0.
Can I use unsigned int i = -3?
What happens internally ? What conversion happens?
Also on 32 and 64bit machines what happens?
Can anybody explain?
Almost all computers use two's complement notation. This means that to
negate an integer you invert the bits, and then add one, losing the overflow
if any. so 1 becomes 11111110 and then 11111111 (all bits set). Zero becomes
11111111 and then overflows to 00000000, which is correct, -0 equals 0.
Internally the processor often has no concept of negative numbers. This is
because adding and throwing away the overflow, in two's complement, is
exactly the same as negating and subtracting.
However the C standard doesn't guarantee that two's complement will be used.
So we have the situation that trying to express -3 as an unsigned integer is
probably going to produce its twos complement value 11111101 (right extend
the ones to sixteen of thirty-two bits instead of eight), which is a
largeish unsigned value. However you cannot be sure of this, and sometimes
you might manage to trigger an internal trap. So from the point of view of
the C stnadard it is actually better to forget all you know about two's
complement values, and just assume that trying to express a negative integer
as an unsigned is illegal.