C# 字节加法溢出?
我注意到当Byte加Byte时,它会产生int, 是否可以让字节a+字节b,如果溢出,则生成255C# 字节加法溢出?,c#,byte,C#,Byte,我注意到当Byte加Byte时,它会产生int, 是否可以让字节a+字节b,如果溢出,则生成255 Byte a=200; Byte b=200 Byte output = (a+b); // now output equals 144, I want 255 这将引发OverflowException: checked { Byte a=200; Byte b=200 Byte output = (a+b); } 通过这种方式,您可以捕获并处理它: Byte out
Byte a=200;
Byte b=200
Byte output = (a+b); // now output equals 144, I want 255
这将引发OverflowException:
checked
{
Byte a=200;
Byte b=200
Byte output = (a+b);
}
通过这种方式,您可以捕获并处理它:
Byte output;
try
{
checked
{
Byte a=200;
Byte b=200
output = (a+b);
}
}
catch(OverflowException e)
{
output = Byte.MaxValue;
}
Console.WriteLine(output);
但我建议你自己控制你的流量。捕捉异常是一种糟糕的方法,但如果您有复杂的计算,它可能会很麻烦。用数学来代替:
var output = (Byte)Math.Min((int)a+b, Byte.MaxValue);
这将引发OverflowException:
checked
{
Byte a=200;
Byte b=200
Byte output = (a+b);
}
通过这种方式,您可以捕获并处理它:
Byte output;
try
{
checked
{
Byte a=200;
Byte b=200
output = (a+b);
}
}
catch(OverflowException e)
{
output = Byte.MaxValue;
}
Console.WriteLine(output);
但我建议你自己控制你的流量。捕捉异常是一种糟糕的方法,但如果您有复杂的计算,它可能会很麻烦。用数学来代替:
var output = (Byte)Math.Min((int)a+b, Byte.MaxValue);
这个未经测试的怎么样
byte output = (byte)(Math.Min(a + b, Byte.MaxValue));
这个未经测试的怎么样
byte output = (byte)(Math.Min(a + b, Byte.MaxValue));
这通常发生在一个数字溢出时,而该数字不在一个列表中 如果你想让它产生255,那么我能想到的最简单的选择就是使用三元运算:
byte output = (int)a + (int)b > byte.MaxValue ? byte.MaxValue : a + b;
我能想到的另一个选择是创建自己的数据类型,为您处理此问题。当一个数字溢出时,通常会发生这种情况,而该数字不在一个表中 如果你想让它产生255,那么我能想到的最简单的选择就是使用三元运算:
byte output = (int)a + (int)b > byte.MaxValue ? byte.MaxValue : a + b;
我能想到的另一个选择是创建自己的数据类型,为您处理此问题。由于a+b是int类型,您可以轻松检查:
Byte a = 200;
Byte b = 200
byte result = a + b > byte.MaxValue ? byte.MaxValue : (byte) (a + b);
由于a+b为int型,您可以轻松检查:
Byte a = 200;
Byte b = 200
byte result = a + b > byte.MaxValue ? byte.MaxValue : (byte) (a + b);
可能byte.MaxValue比magic常量255可读性好一点可能byte.MaxValue比magic常量255可读性好一点你确定这是个好主意吗?它背后的要求是什么?看看:现在输出-a不再等于b了!你确定那是个好主意吗?它背后的要求是什么?看看:现在输出-a不再等于b了!