c# unchecked关键字。byte 合并short

时间:2023-03-08 17:40:31
c# unchecked关键字。byte 合并short

参考MSDN

代码:

 public class BytesOperate
{
/// <summary>
/// 计算校验和,SUM
/// </summary>
public byte CalculateCheckSum(byte[] data)
{
int sum = data.Aggregate(, (current, t) => current + t);
return (byte)(sum & 0x00ff);
} public short CombineBytesToShort(byte high, byte low)
{
short value = (short) (high << );
value += low;
return value ;
}
}
 BytesOperate bytesOperate = new BytesOperate();
Assert.AreEqual(, bytesOperate.CombineBytesToShort(0x01, 0x06));
Assert.AreEqual(-, bytesOperate.CombineBytesToShort(0xff, 0xfe));
Assert.AreEqual(-1.6, (double)bytesOperate.CombineBytesToShort(0xff, 0xf0) / );

使用unchecked:

        [TestMethod]
public void SignedTest()
{
int valueInt = 0xfff0;
Console.WriteLine("原始值:"+ valueInt);
Console.WriteLine("原始值十六进制:"+ valueInt.ToString("x"));
byte high = (byte)(valueInt >> );
Console.WriteLine("高位值:"+high);
Console.WriteLine("高位值十六进制:"+high.ToString("x"));
byte low = (byte)valueInt;
Console.WriteLine("低位值:"+low);
Console.WriteLine("低位值十六进制:"+low.ToString("x"));
short valueShort =(short)(high << ); Console.WriteLine("高位左移8:"+valueShort);
Console.WriteLine("高位左移8十六进制:"+valueShort.ToString("X"));
valueShort += low;
Console.WriteLine("加上低位"+valueShort);
Console.WriteLine(valueShort);
Console.WriteLine(valueShort.ToString("X"));
Assert.AreEqual(-,valueShort); unchecked
{
short anotherValue = (short)0xfff0;
Assert.AreEqual(-,anotherValue);
}
}