类型转换如何从double到byte工作
c#
我有一个代码,其中类型转换返回的值与较大的值大不相同。
static void Main(string[] args)
{
double a = 345.09;
byte c = (byte) a;
Console.WriteLine(c);
Console.ReadLine();
}
这将返回值89
。背后的原因是什么?
回答
发生的情况是,当您投射数字时,只取最后 8 位。让我用一个使用整数的例子来解释。为简单起见,我使用 int ,因为如果您double
转换为非浮点数表示,则无论如何都会丢弃小数位。
首先我们看一下数字 345 的二进制表示:
string binaryInt = Convert.ToString(345, 2);
Console.WriteLine(binaryInt);
输出是:
1 0101 1001
当我们现在只取最后 8 位时,即byte
类型的大小:
string eightLastBits = binaryInt.Substring(binaryInt.Length-8);
Console.WriteLine(eightLastBits);
我们得到:
0101 1001
如果我们byte
再次将其转换为,您将看到结果为 89:
byte backAgain = Convert.ToByte(eightLastBits, 2);
Console.WriteLine(backAgain);
输出:
89
编辑:
正如InBetween所指出的,int 示例是真正的交易以及在铸造过程中真正发生的事情。
纵观实现双到字节的转换:
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(m_value);
}
如果我们查看Convert.ToByte方法的实现:我们会看到 double if 首先转换为整数:
public static byte ToByte(double value) {
return ToByte(ToInt32(value));
}
- I guess this is the reason behind range of byte type. `255` in binary = `11111111`(max limit of 8 bits) Cool I learned a new thing today. Every day is a school day..