zoukankan      html  css  js  c++  java
  • 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);
                }
            }
  • 相关阅读:
    sed
    zabbix时间不同步
    zabbix-agent安装
    zabbix安装(网络)
    sendmail启动报错
    12306:被骂十年不吭声,终成大器
    一文带你看清HTTP所有概念(转)
    为什么 K8s 在阿里能成功(转)
    一文解读融资方式
    一文解读工业互联网 (转)
  • 原文地址:https://www.cnblogs.com/pangkang/p/6089198.html
Copyright © 2011-2022 走看看