提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
关于异或和校验是:对前 5 个字节进行异或和校验得出一个字节的校
验位。
例如对 55 01 A1 5F 00 进行校验得出的值就是 AA
一,用法
1.引入库
代码如下(示例):
/// <summary>
/// 指令生成
/// </summary>
/// <param name="type">类型:A1 开锁</param>
/// <param name="boxNo">箱号</param>
/// <returns></returns>
public string GetDoorCommand(string type, int boxNo)
{
string order = "";
string boxNostr = boxNo.ToString("X2");
if (type == "A1")
{
string StrSendCommand = $"55{boxNostr}A15F00";
byte[] datas = XOR8Helper.hexStrToByte(StrSendCommand);
byte temp = XOR8Helper.GetXOR(datas);
string Value = temp.ToString("X2");
order = StrSendCommand + Value;
}
return order;
}
2.帮助类
代码如下(示例):
using System;
using System.Collections.Generic;
using System.Text;
namespace Haier_Common
{
public class XOR8Helper
{
#region 校验和
public static string GetStrXORValue(string hexstr)
{
byte[] datas = hexStrToByte(hexstr);
byte temp = GetXOR(datas);
string Value= temp.ToString("X2");
return Value;
}
/// <summary>
/// 计算按位异或校验和(返回校验和值)
/// </summary>
/// <returns>校验和值</returns>
public static byte GetXOR(byte[] datas)
{
byte temp = datas[0];
for (int i = 1; i < datas.Length; i++)
{
temp ^= datas[i];
}
return temp;
}
//十六进制字符串转换成字节数组
public static byte[] hexStrToByte(string hexstr)
{
int len = (hexstr.Length / 2);
byte[] result = new byte[len];
char[] achar = hexstr.ToCharArray();
for (int i = 0; i < len; i++)
{
int pos = i * 2;
result[i] = (byte)(((byte)"0123456789ABCDEF".IndexOf(achar[pos])) << 4 | ((byte)"0123456789ABCDEF".IndexOf(achar[pos + 1])));
}
return result;
}
#endregion
}
}