C# 的异或校验算法 直接上代码

   public partial class FormCRC : Form
{
public FormCRC()
{
InitializeComponent();
} private void FormCRC_Load(object sender, EventArgs e)
{ }
/// <summary>
/// CRC异或校验
/// </summary>
/// <param name="cmdString">命令字符串</param>
/// <returns></returns>
private static string CRC(string cmdString)
{
try
{
//CRC寄存器
int CRCCode = 0;
//将字符串拆分成为16进制字节数据然后两位两位进行异或校验
for (int i = 1; i < cmdString.Length / 2; i++)
{
string cmdHex = cmdString.Substring(i * 2, 2);
if (i == 1)
{
string cmdPrvHex = cmdString.Substring((i - 1) * 2, 2);
CRCCode = (byte)Convert.ToInt32(cmdPrvHex, 16) ^ (byte)Convert.ToInt32(cmdHex, 16);
}
else
{
CRCCode = (byte)CRCCode ^ (byte)Convert.ToInt32(cmdHex, 16);
}
}
return Convert.ToString(CRCCode, 16).ToUpper();//返回16进制校验码
}
catch
{
throw;
}
} private void btnConvert_Click(object sender, EventArgs e)
{
try
{
txtCRCCode.Text = CRC(txtCMDString.Text.Replace(" ", ""));
}
catch
{
MessageBox.Show("校验失败,请检查字符串是否包含特殊字符");
}
}
}

  执行结果:

C# 异或校验算法-LMLPHP

05-11 18:38