I have the following code:
short myShort = 23948;
byte myByte = (byte)myShort;
Now I wasn’t expecting myByte to contain the value 23948. I would have guessed that it would contain 255 (I believe the largest value for a byte).
However, it contains 140, and it made me wonder why; what is actually going on behind the scenes?
Please note that I am not looking for someone to solve the problem that 23948 cannot fit into a byte, I am merely wondering about the underlying implementation
Short is a 2-byte type and a byte is, well, a single byte. When you cast from two bytes to one you’re forcing the system to make things fit and one of the original bytes (the most significant) gets dropped and data is lost. What is left from the value of 23948 (binary: 0101 1101 1000 1100) is 140 which in binary translates to 1000 1100. So you are going from:
to:
You can only do this with an explicit cast. If you tried assigning a short to a byte without a cast the compiler would throw an error because of the potential for loss of data:
If you cast from a byte to a short on the other hand you could do it implicitly since no data would be getting lost.
With arithmetic overflow and unchecked context: