c# unchecked关键字。byte 合并short

参考MSDN

代码:

 public class BytesOperate
    {
        /// <summary>
        /// 计算校验和,SUM
        /// </summary>
        public byte CalculateCheckSum(byte[] data)
        {
            int sum = data.Aggregate(0, (current, t) => current + t);
            return (byte)(sum & 0x00ff);
        }

        public short CombineBytesToShort(byte high, byte low)
        {
            short value = (short) (high << 8);  
            value += low;
            return   value ;
        }
    }
 BytesOperate bytesOperate = new BytesOperate();
            Assert.AreEqual(262, bytesOperate.CombineBytesToShort(0x01, 0x06));
            Assert.AreEqual(-2, bytesOperate.CombineBytesToShort(0xff, 0xfe));
            Assert.AreEqual(-1.6, (double)bytesOperate.CombineBytesToShort(0xff, 0xf0) / 10);

使用unchecked:

        [TestMethod]
        public void SignedTest()
        {
            int valueInt = 0xfff0;
            Console.WriteLine("原始值:"+ valueInt);
            Console.WriteLine("原始值十六进制:"+ valueInt.ToString("x"));
            byte high = (byte)(valueInt >> 8);
            Console.WriteLine("高位值:"+high);
            Console.WriteLine("高位值十六进制:"+high.ToString("x"));
            byte low = (byte)valueInt;
            Console.WriteLine("低位值:"+low);
            Console.WriteLine("低位值十六进制:"+low.ToString("x"));
            short valueShort =(short)(high << 8);

            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(-16,valueShort);

            unchecked
            {
                short anotherValue = (short)0xfff0;
                Assert.AreEqual(-16,anotherValue);
            }
        }
原文地址:https://www.cnblogs.com/pangkang/p/6089198.html