当你从短于C#转换为字节会发生什么? [英] What happens when you cast from short to byte in C#?

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

问题描述

我有以下代码:

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

现在我没想到 myByte 来包含我也能猜到它将包含255价值23948.(我相信一个字节的最大值)。

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不能放入一个字节,我的问题只是想了解一下底层实现

推荐答案

短则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)

您只能使用有明确的转换做到这一点。如果你试过没有投分配短一个字节,编译器会抛出一个错误,因为数据丢失的潜在的:

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

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

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