binary representation in turbo c
Question
I have a very basic query. For the following code:
int i = -1;
unsigned int j = (unsigned int) i;
printf("%d",j); // I get 65535 the int limit in turbo C 16 bit compiler
Shouldn't it simply drop the negative sign or does it wrap around the limits ?
Solution
The scheme most commonly used to represent negative numbers is called Two's Complement. In this scheme -1
has the bit pattern of all 1
bits: 1111 1111 1111 1111
. When interpreted as an unsigned integer, which is what your cast means, that's 65535.
In other words, it does "simply drop the negative sign", except that doing so has a different effect than what you expect.
OTHER TIPS
When converting an int
to unsigned int
, if the value is negative the result is as if that negative value has been added to the number one larger than what an unsigned int
can hold. This is specified by the C standard since C90, and holds regardless of whether the machine uses two's complement, one's complement or signed magnitude representations.