in Programming in C retagged by
337 views
0 votes
0 votes
i have typed the following code but when i executed it the solution was not according to my expectation.

unsigned short int y= -9;  int iy=y; printf(“%d”,iy);  

solution given by computer is 65527

but i expect the solution to be -9

does unsigned short affecting my solution in any way.
in Programming in C retagged by
337 views

1 Answer

0 votes
0 votes

There are multiple things happening here.

“-9” will be scanned by the lexical analyzer and it’ll be treated as an integer constant preceded by minus operator which will return negative of “9”.

This negative of 9 will be stored to the memory address of y. Size of short int is 2 bytes. So, “-9” will be stored using “16” bits and let’s assume a 2’s complement representation. So, $2^{16} – 9 = 65536 – 9 = 65527$ will be stored in the memory location of “y”. 

Now, int iy = y; 

Here, y will return “65527” which will be copied to the memory location of “iy” (for now consider 4 bytes for int). 

So, “%d” or “%u” iy will print “65527” and “%hd” y should print “-9” and “%hu” y should print “65527”.

3 Comments

edited by

Binary representation of 65527 in 16 bit will be 1111 1111 1111 0111

int iy=y will promote this in 4Byte so 1111 1111 1111 1111 1111 1111 1111 0111

printf(%d,iy) will print -9 as it will treat it as signed integer

@gatecse Please Correct me where i’m doing wrong??

https://onlinegdb.com/tAXUGIQVk

0
0
When you promoted from 2 bytes to 4 bytes what made you add “1”s to the left and not “0”s?
0
0

@gatecse yes sir

0
0

Related questions