#region 文本处理
#region 字符串转等效数组
/// <summary>
/// 字符串转等效数组
/// </summary>
/// <param name="data">原料</param>
/// <returns>成品</returns>
public byte[] StringsToHexBytes(string data)//change转换,string等效的byte[]
{
//清除所有空格
string str = data.Replace(" ", "");
//若字符个数为奇数,补一个0
str += str.Length % 2 != 0 ? "0" : "";
byte[] bytes = new byte[str.Length / 2];//用于返回结果
for (int i = 0, c = bytes.Length; i < c; i++)//获取bytes值
{
bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
}
return bytes;
}
#endregion
#region 数组转等效字符串
/// <summary>
/// 数组转等效字符串
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public string BytesToHexStrings(byte[] data)//change转换 , byte[ ]等效的string
{
string str = string.Empty;
for (int i = 0; i < data.Length; i++)
{
str += data[i].ToString("X2");
}
return str;
}
#endregion
#region 数组计算CRC
/// <summary>
/// 数组计算CRC
/// </summary>
/// <param name="bytes">原料</param>
/// <param name="b">false小端</param>
/// <returns></returns>
public byte[] getCRC16(byte[] bytes, bool b)//数组,端向,默认flase小端
{
int len = bytes.Length;
if (len > 0)
{
ushort crc = 0xFFFF;
for (int i = 0; i < len; i++)
{
crc = (ushort)(crc ^ (bytes[i]));
for (int j = 0; j < 8; j++)
{
crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
}
}
byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
byte lo = (byte)(crc & 0x00FF); //低位置
if (b)//端向
{
return new byte[] { hi, lo };//大端
}
else
{//默认小端
return new byte[] { lo, hi, };//小端
}
}
return new byte[] { 0, 0 };
}
/// <summary>
/// 字符串计算CRC
/// </summary>
/// <param name="cmd">字符串</param>
/// <returns>CRC</returns>
public string getCRC16(string cmd)
{
return BytesToHexStrings(getCRC16(StringsToHexBytes(cmd), false));//CRC
}
#endregion
#region StringCMD
/// <summary>
/// 完整的命令
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public string StringCMD(string data)//转换 带CRC的命令(用于ui查看)
{
//return data + BytesToHexStrings(getCRC16(StringsToHexBytes(data), false));//命令+CRC
return data + getCRC16(data); // 命令 + CRC
}
#endregion
#region TxCMD
/// <summary>
/// 发送的数据帧
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public byte[] TxCMD(string data)//change转换 串口发送命令
{
data.Replace(" ", "");//去除空白
byte[] buffer = StringsToHexBytes(data);
return buffer;//TX的
}
#endregion
#endregion
06-08
256
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-24
505
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-19
1808
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)