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

后端 未结 4 1214
再見小時候
再見小時候 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:55

    When I first looked at the problem, my initial view was that the char 'c' should be shifted left 8 bits - all 8 bits being discarded, the empty char would then be cast to an int of value 0.

    A bit of research reveals Usual Unary Conversions - this is where to reduce the large number of arithmetic types, conversions are applied automatically to operands of the unary '!', '-', '~' and '*' operators, and to each of the operands of the binary '<<' and '>>' operators.

    Therefore the char 'c' is converted to an int first, then shifted left, giving the answer you see.

    You learn something new every day!

提交回复
热议问题