C# 異或校驗算法
阿新 • • 發佈:2018-09-28
oid tar param .text src 校驗碼 crc summary nco
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# 異或校驗算法