**New course!**Every coder should learn

**Generative AI!**

0

# Why the output is -2?

#include <stdio.h> int main(){ short int a=32767; a=a*2; printf("%d",a); return 0; }

3 Answers

+ 2

In binary 32767 is
0111 1111 1111 1111
And 2 is
0000 0000 0000 0010
And when you multiply these two binary numbers together you get
1111 1111 1111 1110
Which in decimal is -2 because this is using 2's complement. You can look up binary multiplication if you'd like a walk through of the process.

+ 1

The range of short is -32768 to 32767. 32767*2 = 65534, which is out of the range. Going out of 32767 make it go back to the least value possible, -32768.
32767 + 32767
= -32768 + 32766
= -2

+ 1

Bitwise explanation:
32767 in binary looks like
01111111 11111111
Multiplying by 2 will shift bits to the left by 1 place
11111111 11111110
^
The highest bit is the sign bit. It was 0 and now it is 1, which means negative.
Negative numbers are interpreted according to "two's complement" standard, which is equivalent to flipping all bits and adding 1. Let's see what happens...
Flip all bits
-00000000 00000001
Add 1
-00000000 00000010
= -2 in decimal