Why the output is -2? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis
0

Why the output is -2?

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

4th May 2021, 1:07 PM
Abhi
3 Respostas
+ 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.
4th May 2021, 1:32 PM
Odyel
Odyel - avatar
+ 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
4th May 2021, 1:19 PM
šĹ†Áü•ťĀŹŚČáԾƜąĎšĻüśėĮ
šĹ†Áü•ťĀŹŚČáԾƜąĎšĻüśėĮ - avatar
+ 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
4th May 2021, 1:42 PM
Brian
Brian - avatar