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.
The left shift operator ( << ) shifts the first operand the specified number of bits, modulo 32, to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.
Bitshifting shifts the binary representation of each pixel to the left or to the right by a pre-defined number of positions. Shifting a binary number by one bit is equivalent to multiplying (when shifting to the left) or dividing (when shifting to the right) the number by 2.
Bit shifting is an operation done on all the bits of a binary value in which they are moved by a determined number of places to either the left or right. Bit shifting is used when the operand is being used as a series of bits rather than as a whole.
The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.
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));
You are shifting 255 by 1 bit, then trying to assign it to a byte.
255 << 1 is 510
, and 510 won't fit in to a byte.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With