MODBUS协议解析中常用的转换帮助类(C#)
由于经常进行数据对接,解析Modbus协议,把常用的几个帮助类做一记录,方便随时查阅,类中包含CRC16校验,进制之间的转换等。
/*********************************************
* 命名空间:ModbusServer.Common
* 功 能: 数据转换帮助类
* 类 名: ConvertTools
* 作 者: 东腾
* 时 间: 2018-09-26 10:20:00
**********************************************
*/ using System;
using System.Globalization;
using System.Linq;
using System.Text; namespace ModbusServer.Common
{
public sealed class ConvertTools
{
/// <summary>
/// 字符串转换为Hex字符串
/// </summary>
/// <param name="s">字符串</param>
/// <param name="encode">编码类型</param>
/// <returns></returns>
public static string StringToHexString(string s, Encoding encode)
{
var b = encode.GetBytes(s); //按照指定编码将string编程字节数组
return b.Aggregate(string.Empty, (current, t) => current + "%" + Convert.ToString(t, ));
} /// <summary>
/// Hex字符串转换为字符串
/// </summary>
/// <param name="hs">Hex字符串</param>
/// <param name="encode">编码类型</param>
/// <returns></returns>
public static string HexStringToString(string hs, Encoding encode)
{
//以%分割字符串,并去掉空字符
var chars = hs.Split(new[] {'%'}, StringSplitOptions.RemoveEmptyEntries);
var b = new byte[chars.Length];
//逐个字符变为16进制字节数据
for (var i = ; i < chars.Length; i++) b[i] = Convert.ToByte(chars[i], ); //按照指定编码将字节数组变为字符串
return encode.GetString(b);
} /// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString">Hex字符串</param>
/// <returns></returns>
public static byte[] StringToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if (hexString.Length % != )
hexString += " ";
var returnBytes = new byte[hexString.Length / ];
for (var i = ; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * , ), );
return returnBytes;
} /// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes">bytes</param>
/// <returns></returns>
public static string BytesToHexString(byte[] bytes)
{
const string returnStr = "";
return bytes == null ? returnStr : bytes.Aggregate(returnStr, (current, t) => current + t.ToString("X2"));
} /// <summary>
/// 将byte[]转换成int
/// </summary>
/// <param name="data">需要转换成整数的byte数组</param>
public static int BytesToInt32(byte[] data)
{
//如果传入的字节数组长度小于4,则返回0
if (data.Length < ) return ; //定义要返回的整数
var num = ;
//如果传入的字节数组长度大于4,需要进行处理
if (data.Length < ) return num;
//创建一个临时缓冲区
var tempBuffer = new byte[];
//将传入的字节数组的前4个字节复制到临时缓冲区
Buffer.BlockCopy(data, , tempBuffer, , );
//将临时缓冲区的值转换成整数,并赋给num
num = BitConverter.ToInt32(tempBuffer, );
//返回整数
return num;
} /// <summary>
/// bytes数据转换为float类型
/// </summary>
/// <param name="data">byte数据</param>
/// <returns></returns>
public static float ValueConvertToFloat(byte[] data)
{
var shuju = BytesToHexString(data);
var num = uint.Parse(shuju, NumberStyles.AllowHexSpecifier);
var floatValues = BitConverter.GetBytes(num);
return BitConverter.ToSingle(floatValues, );
} /// <summary>
/// bytes数据转换为long类型
/// </summary>
/// <param name="data">byte数据</param>
/// <returns></returns>
public static long ValueConvertToLong(byte[] data)
{
var shuju = BytesToHexString(data);
var num = ulong.Parse(shuju, NumberStyles.AllowHexSpecifier);
return (long) num;
} public static byte[] CRC16(byte[] data)
{
ushort crc = 0xFFFF; //set all 1 var len = data.Length;
if (len <= )
{
crc = ;
}
else
{
len--;
uint ix;
for (ix = ; ix <= len; ix++)
{
crc = (ushort) (crc ^ data[ix]);
uint iy;
for (iy = ; iy <= ; iy++)
if ((crc & ) != )
crc = (ushort) ((crc >> ) ^ 0xA001);
else
crc = (ushort) (crc >> ); //
}
} var buf1 = (byte) ((crc & 0xff00) >> ); //高位置
var buf2 = (byte) (crc & 0x00ff); //低位置
crc = (ushort) (buf1 << );
crc += buf2;
var strA = crc.ToString("x4");
var result = StringToHexByte(strA);
var b = new byte[];
b[] = result[];
b[] = result[];
return b;
}
}
}
-->