Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

short int Integer wrap around / short int inversion in c not understood, difference between assignment and prints

The following code fragment

short int k = -32768;
printf("%d \n", -k);
k=-k;
printf("%d \n", k);

prints

32768 
-32768

I would assume that both prints are equal. Can somebody explain what the difference is and why the assignment k=-k causes a wrap around? It was hard to find a explanation online, as i don't really know what to google.

like image 661
Falco Winkler Avatar asked Mar 09 '17 17:03

Falco Winkler


3 Answers

Well, to print a short, you need to use a length modifier.

Change the format string to %hd.

like image 91
Sourav Ghosh Avatar answered Oct 19 '22 12:10

Sourav Ghosh


Because SHRT_MIN = -32768 and SHRT_MAX = +32767. Check out how 2's complement work.

Edit

Actually, according to the international standard of the C programming language (i.e. Committee Draft — May 6, 2005, pp. 50-51) regarding signed integers:

For signed integer types, the bits of the object representation shall be divided into three groups: value bits, padding bits, and the sign bit.

There need not be any padding bits; there shall be exactly one sign bit.

Each bit that is a value bit shall have the same value as the same bit in the object representation of the corresponding unsigned type (if there are M value bits in the signed type and N in the unsigned type, then M <= N).

If the sign bit is zero, it shall not affect the resulting value.

If the sign bit is one, the value shall be modified in one of the following ways:

  • the corresponding value with sign bit 0 is negated (sign and magnitude);

  • the sign bit has the value −(2N ) (two's complement);

  • the sign bit has the value −(2N − 1) (ones' complement).

Which of these applies is implementation-defined, as is whether the value with sign bit 1 and all value bits zero (for the first two), or with sign bit and all value bits 1 (for ones' complement), is a trap representation or a normal value. In the case of sign and magnitude and ones' complement, if this representation is a normal value it is called a negative zero.

So, in other words, in your case it's seems that 2's complement is being used, but this should not be assumed to be in all platforms and compilers.

like image 2
nbro Avatar answered Oct 19 '22 11:10

nbro


-32768 is 8000 in hexadecimal notation. 32768 can not be represented as a signed 16 bit number, therefore the compiler promotes -k to an int with the hex value 00008000. When this number is assigned to the 16-bit variable, the high bits are truncated, resulting in 8000 or -32768 again.

like image 1
alain Avatar answered Oct 19 '22 11:10

alain