Numberknot
Numberknot

Reputation: 149

strange behaviour of char

If char a = -128; it is represented in binary as 10000000.

but when I shift this binary equivalent to the left side by by one bit it gives me -256 for which my brain doesn't make any sense.

Can anyone explain it to me how this strange behaviour comes?

int main(){
char  a=-128;
printf("%d",a<<1);
return 0;   
 }

Upvotes: 2

Views: 97

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

As per the rule# of shifting operator,

The integer promotions are performed on each of the operands. [...]

So, while using a<<1 as the argument for printf(), a being of type char and 1 being the type of int (literal), a value is promoted to type int and then, the shifting will be performed, then the result will be printed out as an int value.


[#] - C11, chapter §6.5.7, Bitwise shift operators

Upvotes: 4

LPs
LPs

Reputation: 16243

-128 on an int variable is 0xffffff80.

The shifting left result is 0xffffff00 that is -256.

You can test it with this code:

int main(void) 
{
    int n = -128;

    printf("Decimal value = %d\n", n);
    printf("Hex value = %x\n", n);

    n<<=1;

    printf("Decimal value = %d\n", n);
    printf("Hex Value = %x\n", n);

    return 0;
}

EDIT In your code printf is promoting your char variable to int before shifting it.

Upvotes: 4

Related Questions