In C Left shift (char) 0xFF by 8 and cast it to int

后端 未结 4 1203
再見小時候
再見小時候 2020-12-17 17:26

On left shift of (char) 0xff by 8 and casting it to int we get -256 or 0xffffff00. Can somebody explain why this should happen?

#include 
int         


        
4条回答
  •  自闭症患者
    2020-12-17 17:56

    char can be signed or unsigned - it's implementation-defined. You see these results because char is signed by default on your compiler.

    For the signed char 0xFF corresponds to −1 (that's how two's complement work). When you try to shift it it is first promoted to an int and then shifted - you effectively get multiplication by 256.

    So it is this code:

    char c = 0xFF; // -1
    int shifted = c << 8; //-256 (-1 * 256)
    printf( "%d, %x", shifted, shifted );
    

提交回复
热议问题