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