user17379750
user17379750

Reputation:

Converting char to short in C

I am considering what the value of ca will be after these operations:

int ca = -279;
char abb = ca;
int ca = /abb >> 6) ;

I am having trouble understanding what happens with ca because of the shifting.

Upvotes: 0

Views: 132

Answers (2)

53845714nF
53845714nF

Reputation: 35

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: @ 

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 222689

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.

Upvotes: 2

Related Questions