0

I have a question.

#include <stdio.h>

int main()
{
    unsigned char i = 0x80;
    printf("%d\n",i<<1);
    return 0;
}

In above program, unsigned char is assigned 0x80(i.e 128). For i<<1, I am getting the value of 256. My doubt here is i = 1000 0000 binary, but how can i<<1 get the value 256 ? why not 0, as (1000 0000)<<1 1 will knocked off ?

dbush
  • 205,898
  • 23
  • 218
  • 273
Sanman
  • 129
  • 1
  • 6
  • 4
    Because the operands to << are first promoted to int. – Oliver Charlesworth Jul 16 '17 at 23:55
  • ISO/IEC 9899:2011 (C) §6.5.7 Bitwise shift operators 3) The integer promotions are performed on each of the operands.The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined. – Miket25 Jul 16 '17 at 23:57

1 Answers1

0

If a variable with a rank lower than int is used in an expression, such as char or unsigned char, it is promoted to an int before the expression is evaluated.

So your unsigned char value 0x80 is converted to the int value 0x80 and the << operator is applied to that. So what was the high order bit is no longer the high order bit, so it doesn't get shifted out.

dbush
  • 205,898
  • 23
  • 218
  • 273