Left bit shifting 255 (as a byte)

2019-01-09 09:49发布

Can anyone explain why the following doesn't compile?

byte b = 255 << 1

The error:

Constant value '510' cannot be converted to a 'byte'

I'm expecting the following in binary:

1111 1110

The type conversion has stumped me.

7条回答
放我归山
2楼-- · 2019-01-09 10:10

And since << has a higher precedence than & you can save the brackets:

byte b = 255 << 1 & 0xff;
查看更多
登录 后发表回答