c# unchecked关键字。byte 合并short
生活随笔
收集整理的這篇文章主要介紹了
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
總結
以上是生活随笔為你收集整理的c# unchecked关键字。byte 合并short的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (Hibernate进阶)Hiberna
- 下一篇: c# char unsigned_dll