Left bit shifting 255 (as a byte)

前端 未结 7 751
臣服心动
臣服心动 2020-12-01 18:41

Can anyone explain why the following doesn\'t compile?

byte b = 255 << 1

The error:

Constant value \'510\' can

7条回答
  •  长情又很酷
    2020-12-01 18:49

    The result of the << operator is an Int32, not what you put into it.

    You need to cast the result of the shift, not the input. Additionally, it will produce an overflow (it is larger than a byte afterall), so you need to specify that you need an unchecked cast.

    In other words, this will work:

    Byte b = unchecked((Byte)(255 << 1));
    

提交回复
热议问题