sparkyShorts sparkyShorts - 3 months ago 29
C# Question

Why Do Bytes Carryover?

I have been playing with some byte arrays recently (dealing with grayscale images). A byte can have values 0-255. I was modifying the bytes, and came across a situation where the value I was assigning to the byte was outside the bounds of the byte. It was doing unexpected things to the images I was playing with.

I wrote a test and learned that the byte carries over. Example:

private static int SetByte(int y)
return y;
byte x = (byte) SetByte(-4);
//output is 252

There is a carryover! This happens when we go the other way around as well.

byte x = (byte) SetByte(259);
//output is 3

I would have expected it to set it to 255 in the first situation and 0 in the second. What is the purpose of this carry over? Is it just due to the fact that I'm casting this integer assignment? When is this useful in the real-world?

byte x = (byte) SetByte(259);
//output is 3

The cast of the result of SetByte is applying modulo 256 to your integer input, effectively dropping bits that are outside the range of a byte.

259 % 256 = 3

Why: The implementers choose to only consider the 8 least significant bits, ignoring the rest.