Left bit shifting 255 (as a byte)

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));

Leave a Comment