Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you cast from short to byte in C#?

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

like image 942
Fiona - myaccessible.website Avatar asked Sep 27 '11 21:09

Fiona - myaccessible.website


2 Answers

It depends; in a checked context, you'll get a big fat exception; in an unchecked context (the default) you get to keep the data from the last byte, the same as if you did:

byte b = (byte)(value & 255);
like image 92
Marc Gravell Avatar answered Oct 02 '22 23:10

Marc Gravell


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:

0101 1101 1000 1100 (2 byte decimal value 23948)

to:

          1000 1100 (1 byte decimal value 140)

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:

Cannot implicitly convert type 'short' to 'byte'. An explicit conversion exists (are you missing a cast?)

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.

using System;
public class MyClass
{
    public static void Main()
    {
        short myShort = 23948;
        byte myByte = (byte)myShort; // ok
        myByte = myShort; // error: 

        Console.WriteLine("Short: " + myShort);
        Console.WriteLine("Byte:  " + myByte);

        myShort = myByte; // ok

        Console.WriteLine("Short: " + myShort);
    }
}

With arithmetic overflow and unchecked context:

using System;
public class MyClass {
    public static void Main() {
        unchecked {
            short myShort = 23948;
            byte myByte = (byte)myShort; // ok
            myByte = myShort; // still an error
            int x = 2147483647 * 2; // ok since unchecked
        }   
    }
}
like image 23
Paul Sasik Avatar answered Oct 02 '22 21:10

Paul Sasik