Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

casting - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
        }   
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...