I am considering what the value of sg will be after these operations:
short sa = -279;
char cb = (char) sa;
short sg = (cb << 8) >> 2;
I am having trouble understanding what happens with sg because of the shifting.
I would think that cb would overflow due to the 8 shift to the left and then end up being 0? But when I run the code in C and print using printf, I get -1216.
Can anyone explain why this happens?
CodePudding user response:
It appears likely that, in your C implementation, char
is signed and eight bits. In (char) sa
, the value of sa
, −275, cannot be represented in the char
type. The C standard requires each C implementation to define what it does here, which must be either to produce a value or a trap. It appears your C implementation wraps the value modulo 256, so −275 becomes −275 256 = −19.
In cb << 8
, cb
is promoted to int
. In your C implementation, int
is probably 32 bits, as that is common in implementations that C students use these days. However, left-shifting a negative value is not defined by the C standard. It appears your C implementation produced −4,864, equal to multiplying −19 by 256 or to shifting a two’s complement −19 eight bits to the left.
Then we effectively have -4864 >> 2
. The C standard says right-shifting a negative value is implementation-defined. It appears your C implementation performed an arithmetic shift. This produced −1,216.
CodePudding user response:
I think short is environment dependent,so you can try this in your environment with printf.
#include <stdio.h>
#include <limits.h>
int main(){
printf("Short Max: %hi \n", SHRT_MAX);
printf("Short Min: %hi \n", SHRT_MIN);
printf("Char Max: %i \n", CHAR_MAX);
printf("Char Min: %i \n", CHAR_MIN);
short sa = -275;
printf("Short: %hi Char: %c\n", sa, sa);
char cb = (char) sa;
printf("Short: %hi Char: %c\n", cb, cb );
short sg = (cb << 8) >> 2;
printf("Short: %hi Char: %c \n", sg, sg);
return 0;
}
I get the following:
Short Max: 32767
Short Min: -32768
Char Max: 127
Char Min: -128
Short: -275 Char: �
Short: -19 Char: �
Short: -1216 Char: @