Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left bit shifting 255 (as a byte)

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.

like image 350
Chris S Avatar asked Apr 10 '09 14:04

Chris S


People also ask

How do you shift a bit to the left?

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.

What does bit shifting by 1 do?

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.

What is bit shifting in memory?

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.

Which is used to shift all of the bits in a value to the left side of a specified number of times?

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.


2 Answers

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));
like image 191
Joey Avatar answered Sep 21 '22 07:09

Joey


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.

like image 36
Steve Avatar answered Sep 23 '22 07:09

Steve