Left bit shifting 255 (as a byte)

Chris S picture Chris S · Apr 10, 2009 · Viewed 28.3k times · Source

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.

Answer

Joey picture Joey · Apr 10, 2009

Numeric literals in C# are int, not byte (and the bit shift will be evaluated by the compiler, hence only the 510 remains). You are therefore trying to assign a value to a byte which does not fit. You can mask with 255:

byte b = (255 << 1) & 0xFF

to reduce the result to 8 bits again. Unlike Java, C# does not allow overflows to go by undetected. Basically you'd have two sensible options when trying to assign 510 to a byte: Either clamp at the maximum value, then you'd get 255, or throw away the bits that do not fit, in which case you'd get 254.

You can also use unchecked, as lassevk mentioned:

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