YUN
学习工作赚钱对象是正事
学习编程技术

C#上位机常用字节转换

字节转化常用方法封装

   public class ByteHelper_V2
   {
       /// <summary>
       /// 3字节的有符号数字转换为有符号整形32位数字
       /// </summary>
       /// <param name="bytes">长度为3的字节数组</param>
       /// <returns></returns>
       public static int Byte3ToInt(byte[] bytes)
       {
           int number = (((int)bytes[0]) << 16) | (((int)bytes[1]) << 8) | bytes[2];
           if ((number & 0x800000) == 0x800000)//如果最高位是1,即负数
           {
               number = (int)(number | 0xff000000);
           }
           return number;
       }
       /// <summary>
       /// 3字节的有符号数字转换为有符号整形32位数字
       /// </summary>
       /// <param name="sours"></param>
       /// <param name="index"></param>
       /// <param name="count"></param>
       /// <returns></returns>
       public static int Byte3ToInt(byte[] sours, int index, int count)
       {
           var bytes = ByteHelper_V2.ByteCopy(sours, index, count);
           int number = (((int)bytes[0]) << 16) | (((int)bytes[1]) << 8) | bytes[2];
           if ((number & 0x800000) == 0x800000)//如果最高位是1,即负数
           {
               number = (int)(number | 0xff000000);
           }
           return number;
       }

       public static byte[] IntToByte3(int value)
       {
           byte[] bytes = new byte[3];
           bytes[0] = (byte)((value >> 16) & 0xFF);
           bytes[1] = (byte)((value >> 8) & 0xFF);
           bytes[2] = (byte)(value & 0xFF);
           return bytes;
       }
       /// <summary>
       /// 无符号字节数组转换为int
       /// </summary>
       /// <param name="bytes">字节数组(长度1~4)</param>
       /// <returns></returns>
       public static int UByteToInt(byte[] sours, int index, int count)
       {
           int number = 0;
           var bytes = ByteHelper_V2.ByteCopy(sours, index, count);
           for (int i = 0; i < bytes.Length; i++)
           {
               number = (int)(number ^ bytes[i]);
               if (i + 1 < bytes.Length)
                   number = (int)(number << 8);
           }
           return number;
       }
       /// <summary>
       /// 无符号字节数组转换为int
       /// </summary>
       /// <param name="bytes">字节数组(长度1~4)</param>
       /// <returns></returns>
       public static int UByteToInt(List<byte> sours, int index, int count)
       {
           int number = 0;
           var bytes = ByteCopy(sours, index, count);
           for (int i = 0; i < bytes.Length; i++)
           {
               number = (int)(number ^ bytes[i]);
               if (i + 1 < bytes.Length)
                   number = (int)(number << 8);
           }
           return number;
       }

       /// <summary>
       /// 无符号字节数组转换为int
       /// </summary>
       /// <param name="bytes">字节数组(长度1~4)</param>
       /// <returns></returns>
       public static int UByteToInt(byte[] bytes)
       {
           int number = 0;
           for (int i = 0; i < bytes.Length; i++)
           {
               number = (int)(number ^ bytes[i]);
               if (i + 1 < bytes.Length)
                   number = (int)(number << 8);
           }
           return number;
       }
       public static long UByteToLong(byte[] bytes)
       {
           long number = 0;
           for (int i = 0; i < bytes.Length; i++)
           {
               number = (long)(number ^ bytes[i]);
               if (i + 1 < bytes.Length)
                   number = (long)(number << 8);
           }
           return number;
       }
       /// <summary>
       /// 无符号字节数组转换为int
       /// </summary>
       /// <param name="byte1"></param>
       /// <param name="byte2"></param>
       /// <param name="byte3"></param>
       /// <param name="byte4"></param>
       /// <returns></returns>
       public static int UByteToInt(byte byte1, byte? byte2 = null, byte? byte3 = null, byte? byte4 = null)
       {
           int number = 0;
           number = (int)(number ^ byte1);
           if (byte2 != null)
           {
               number = (int)(number << 8);
               number = (int)(number ^ byte2);
           }
           if (byte3 != null)
           {
               number = (int)(number << 8);
               number = (int)(number ^ byte3);
           }
           if (byte4 != null)
           {
               number = (int)(number << 8);
               number = (int)(number ^ byte4);
           }
           return number;
       }
       /// <summary>
       /// 无符号字节数组转换为int
       /// </summary>
       /// <param name="byte1"></param>
       /// <param name="byte2"></param>
       /// <param name="byte3"></param>
       /// <param name="byte4"></param>
       /// <returns></returns>
       public static int UByteToInt(List<byte> bytes)
       {
           int number = 0;
           if (bytes.Count > 0)
           {
               number = (int)(number ^ bytes[0]);
               for (int i = 1; i < bytes.Count; i++)
               {
                   number = (int)(number << 8);
                   number = (int)(number ^ bytes[i]);
               }
           }
           return number;
       }


       /// <summary>
       /// 带符号的1字节转换为int
       /// </summary>
       /// <param name="bytes"></param>
       /// <returns></returns>
       public static int ByteToInt(byte bytes)
       {
           int number = (int)bytes;
           if ((number & 0x80) == 0x80)
           {
               number = (int)(number | 0xffffff00);
           }
           return number;
       }

       public static float Byte3ToFloat(byte byte1, byte byte2, byte byte3)
       {
           int intPart = (int)(byte1 >> 5);
           int fraPart = (int)(byte1 & 0x1F);
           fraPart = (int)(fraPart << 8);
           fraPart = (int)(fraPart ^ byte2);
           fraPart = (int)(fraPart << 8);
           fraPart = (int)(fraPart ^ byte3);
           float number = (float)(intPart + fraPart / Math.Pow(2, 21));
           return number;
       }


       #region 后加方法


       public static int GetLength(byte[] bytes, int index)
       {
           return ((bytes[index] << 8) | bytes[index + 1]);
       }
       public static int GetLength(List<byte> bytes, int index)
       {
           return ((bytes[index] << 8) | bytes[index + 1]);
       }
       public static byte[] GetLength_Byte(List<byte> bytes)
       {
           var count = bytes.Count;
           byte[] length = new byte[2];
           length[0] = (byte)((count) >> 8 & 0xff);
           length[1] = (byte)((count) & 0xff);
           return length;
       }

       public static string GetStringHex(byte[] byteDatas, int index, int count)
       {
           var resData = BitConverter.ToString(byteDatas, index, count);
           return resData;
           var copyData = ByteCopy(byteDatas, index, count);
           StringBuilder builder = new StringBuilder();
           for (int i = 0; i < copyData.Length; i++)
           {
               builder.Append(string.Format("{0:X2} ", copyData[i]));
           }
           return builder.ToString().Trim();
       }

       public static List<byte> HexStringToBytes(string hexStr)
       {
           List<byte> bytes = new List<byte>();
           foreach (var item in hexStr.Split('-'))
           {
               int value = Convert.ToInt32(item, 16);
               bytes.Add((byte)value);
           }
           return bytes;
       }

       public static string GetStringHex(byte[] byteDatas)
       {
           return BitConverter.ToString(byteDatas);
           StringBuilder builder = new StringBuilder();
           for (int i = 0; i < byteDatas.Length; i++)
           {
               builder.Append(string.Format("{0:X2} ", byteDatas[i]));
           }
           return builder.ToString().Trim();
       }

       public static string GetString(byte[] bytes)
       {
           return Encoding.ASCII.GetString(bytes, 0, bytes.Length);
       }
       public static int GetInt(byte[] bytes, int index)
       {
           return (int)(bytes[index]);
       }
       public static int GetRssi(byte[] bytes, int index)
       {
           return ByteToInt(bytes[index]);

       }
       public static string GetString(byte[] bytes, int index, int count)
       {
           return Encoding.ASCII.GetString(bytes, index, count);
       }
       public static byte[] GetBytes(string data)
       {
           return Encoding.ASCII.GetBytes(data);
       }
       public static byte GetBytes(int data)
       {
           return Convert.ToByte(data);
       }

       public static int GetTimeStamp(byte[] bytes)
       {
           int timeStamp = UByteToInt(bytes[bytes.Length - 4], bytes[bytes.Length - 3], bytes[bytes.Length - 2], bytes[bytes.Length - 1]);
           return timeStamp;
       }

       public static int GetTimeStamp(byte[] bytes, int index)
       {
           int timeStamp = UByteToInt(bytes[index], bytes[index + 1], bytes[index + 2], bytes[index + 3]);
           return timeStamp;
       }
       public static byte[] GetNowTimeStamp_Byte()
       {
           var timeStamp = BitConverter.GetBytes(GetNowTimeStamp_Int()).Reverse().ToArray();
           return timeStamp;
       }
       public static List<byte> GetNowTimeStamp_ByteList()
       {
           var timeStamp = BitConverter.GetBytes(GetNowTimeStamp_Int()).Reverse().ToList();
           return timeStamp;
       }
       public static List<byte> LongToByte(long data)
       {
           var datas = BitConverter.GetBytes(data).Reverse().ToList();
           return datas;
       }
       public static List<byte> IntToBytes(int data)
       {
           var datas = BitConverter.GetBytes(data).Reverse().ToList();
           return datas;
       }
       public static byte IntToByte(int data)
       {
           return (byte)data;
       }


       public static int GetNowTimeStamp_Int()
       {
           //var timeStamp = (int)new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
           var timeStamp = (int)new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
           return timeStamp;
       }
       public static byte[] ByteCopy(byte[] bytes, int index)
       {
           byte[] newBts = new byte[bytes.Length - index];
           Buffer.BlockCopy(bytes, index, newBts, 0, newBts.Length);
           return newBts;
       }
       public static byte[] ByteCopy(List<byte> bytes, int index, int count)
       {
           return bytes.Skip(index).Take(count).ToArray();
       }
       public static byte[] ByteCopy(byte[] bytes, int index, int count)
       {
           byte[] newBts = new byte[count];
           Buffer.BlockCopy(bytes, index, newBts, 0, newBts.Length);
           return newBts;
       }
       public static string GetVersion(byte[] bytes, int index, int count)
       {
           var datas = ByteCopy(bytes, index, count);
           var version = $"{datas[0]}.{datas[1]}.{BitConverter.ToInt16(new byte[] { datas[3], datas[2] })}";
           return version;
       }

       public static bool GetByteToBool(int dt, int loc)
       {
           return ((dt >> loc) & 0x01) == 1;
       }

       public static byte GetByte(int dt, int loc)
       {
           return (byte)((dt >> loc) & 0x01);
       }

       public static DateTime GetTimeBySeconds(int seconds)
       {
           DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
           var time = startTime.AddSeconds(seconds);
           return time;
       }
       #endregion





       #region 16位CRC校验

       /// <summary>
       /// CRC校验,参数data为byte数组
       /// </summary>
       /// <param name="data">校验数据,字节数组</param>
       /// <returns>字节0是高8位,字节1是低8位</returns>
       public static byte[] CRCCalc(byte[] data)
       {
           //crc计算赋初始值
           int crc = 0xffff;
           for (int i = 0; i < data.Length; i++)
           {
               crc = crc ^ data[i];
               for (int j = 0; j < 8; j++)
               {
                   int temp;
                   temp = crc & 1;
                   crc = crc >> 1;
                   crc = crc & 0x7fff;
                   if (temp == 1)
                   {
                       crc = crc ^ 0xa001;
                   }
                   crc = crc & 0xffff;
               }
           }
           //CRC寄存器的高低位进行互换
           byte[] crc16 = new byte[2];
           //CRC寄存器的高8位变成低8位,
           crc16[1] = (byte)((crc >> 8) & 0xff);
           //CRC寄存器的低8位变成高8位
           crc16[0] = (byte)(crc & 0xff);
           return crc16;
       }

       /// <summary>
       /// CRC校验,参数为空格或逗号间隔的字符串
       /// </summary>
       /// <param name="data">校验数据,逗号或空格间隔的16进制字符串(带有0x或0X也可以),逗号与空格不能混用</param>
       /// <returns>字节0是高8位,字节1是低8位</returns>
       public static byte[] CRCCalc(string data)
       {
           //分隔符是空格还是逗号进行分类,并去除输入字符串中的多余空格
           IEnumerable<string> datac = data.Contains(",") ? data.Replace(" ", "").Replace("0x", "").Replace("0X", "").Trim().Split(',') : data.Replace("0x", "").Replace("0X", "").Split(' ').ToList().Where(u => u != "");
           List<byte> bytedata = new List<byte>();
           foreach (string str in datac)
           {
               bytedata.Add(byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier));
           }
           byte[] crcbuf = bytedata.ToArray();
           //crc计算赋初始值
           return CRCCalc(crcbuf);
       }

       /// <summary>
       ///  CRC校验,截取data中的一段进行CRC16校验
       /// </summary>
       /// <param name="data">校验数据,字节数组</param>
       /// <param name="offset">从头开始偏移几个byte</param>
       /// <param name="length">偏移后取几个字节byte</param>
       /// <returns>字节0是高8位,字节1是低8位</returns>
       public static byte[] CRCCalc(byte[] data, int offset, int length)
       {
           byte[] Tdata = data.Skip(offset).Take(length).ToArray();
           return CRCCalc(Tdata);
       }



       #endregion
   }

发表回复

textsms
account_circle
email

学习编程技术

C#上位机常用字节转换
字节转化常用方法封装 public class ByteHelper_V2 { /// <summary> /// 3字节的有符号数字转换为有符号整形32位数字 /// </summary> //…
扫描二维码继续阅读
2024-11-20