在 C# 中从 short 转换为 byte 会发生什么? [英] What happens when you cast from short to byte in C#?

查看:21
本文介绍了在 C# 中从 short 转换为 byte 会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

short myShort = 23948;
byte myByte = (byte)myShort;

现在我没想到 myByte 包含值 23948.我猜它会包含 255(我相信是一个字节的最大值).

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).

然而,它包含 140,这让我想知道为什么;幕后究竟发生了什么?

However, it contains 140, and it made me wonder why; what is actually going on behind the scenes?

请注意,我不是在找人解决 23948 不能放入一个字节的问题,我只是想知道底层实现

推荐答案

Short 是 2 字节类型,而一个字节是单个字节.当您从两个字节转换为一个字节时,您将迫使系统进行调整,原始字节之一(最重要的)被丢弃并且数据丢失.23948 的值(二进制:0101 1101 1000 1100)剩下的是 140,二进制转换为 1000 1100.所以你要从:

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)

到:

          1000 1100 (1 byte decimal value 140)

您只能使用显式强制转换来执行此操作.如果您尝试在没有强制转换的情况下为一个字节分配一个 short ,则编译器将抛出一个错误,因为可能会丢失数据:

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:

无法将类型short"隐式转换为byte".一个明确的转换存在(您是否缺少演员?)

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

另一方面,如果您从一个字节转换为一个 short,您可以隐式地进行转换,因为不会丢失任何数据.

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

这篇关于在 C# 中从 short 转换为 byte 会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆