c - Sign extension query in case of short -
given,
unsigned short y = 0xffff;
when print
printf("%x", y);
i : 0xffff;
but when print
printf("%x", (signed short)y);
i : 0xffffffff
whole programme below:
#include <stdio.h> int main() { unsigned short y = 0xffff; unsigned short z = 0x7fff; printf("%x %x\n", y,z); printf("%x %x", (signed short)y, (signed short)z); homecoming 0; }
sign extension happens when typecast lower higher byte info type, here typecasting short signed short. in both cases sizeof((signed short)y) or sizeof((signed short)z) prints 2 bytes. short remains of 2 bytes, if sign bit 0 in case of 0x7fff. help much appreciated!
output of first printf
expected. sec printf
produces undefined behavior.
in c language when pass a value smaller int
variadic argument, value implicitly converted type int
. not possible physically pass short
or char
variadic argument. implicit conversion int
"sign extension" takes place.
for reason, printf("%x", y);
equivalent printf("%x", (int) y);
. value passed printf
0xffff
of type int
. technically, %x
format requires unsigned int
argument, non-negative int
value ok (unless i'm missing technicality). output 0xffff
.
conversion int
happens in sec case well. i.e. printf("%x", (signed short) y);
equivalent printf("%x", (int) (signed short) y);
. conversion of 0xffff
(signed short)
implementation-defined, because 0xffff
apparently out of range of signed short
on platform. produces negative value (-1
). when converted int
produces same negative value of type int
(again, -1
represented 0xffffffff
32-bit int
). farther behavior undefined, since passing negative int
value format specifier %x
, requires unsigned int
argument. illegal utilize %x
negative int
values.
in other words, formally sec printf
prints unpredictable garbage. practically above explains 0xffffffff
came from.
c
No comments:
Post a Comment