C# 异或校验两种方法
1 2 public byte GetXor(byte[] data) 3 { 4 byte CheckCode = 0; 5 int len = data.Length; 6 for (int i = 0; i < len; i++) 7 { 8 CheckCode ^= data[i]; 9 } 10 return CheckCode; 11 } 12 13 private string CRC(string cmdString) 14 { 15 try 16 { 17 //CRC寄存器 18 int CRCCode = 0; 19 //将字符串拆分成为16进制字节数据然后两位两位进行异或校验 20 for (int i = 1; i < cmdString.Length / 2; i++) 21 { 22 string cmdHex = cmdString.Substring(i * 2, 2); 23 if (i == 1) 24 { 25 string cmdPrvHex = cmdString.Substring((i - 1) * 2, 2); 26 byte t = (byte)Convert.ToInt32(cmdHex, 10); 27 byte tt = (byte)Convert.ToInt32(cmdPrvHex, 10); 28 CRCCode = (byte)Convert.ToInt32(cmdPrvHex, 10) ^ (byte)Convert.ToInt32(cmdHex, 10); 29 } 30 else 31 { 32 CRCCode = (byte)CRCCode ^ (byte)Convert.ToInt32(cmdHex, 16); 33 } 34 } 35 return Convert.ToString(CRCCode, 16).ToUpper();//返回16进制校验码 36 } 37 catch 38 { 39 throw; 40 } 41 } 42 43 private void button1_Click(object sender, EventArgs e) 44 { 45 try 46 { 47 // txtZhi.Text = CRC(textBox1.Text.Replace(" ", "")); 48 byte[] bytes = new byte[6]; 49 bytes[0] = 36; 50 bytes[1] = 50; 51 bytes[2] = 50; 52 bytes[3] = 48; 53 bytes[4] = 50; 54 bytes[5] = 57; 55 string cmd= "$31064";//$ 3 1 064 14 56 ASCIIEncoding ascii = new ASCIIEncoding(); 57 Byte[] encodedBytes = ascii.GetBytes(cmd); 58 byte code = GetXor(encodedBytes); 59 60 txtZhi.Text = cmd+ Convert.ToString(code, 16).ToUpper(); 61 } 62 catch 63 { 64 MessageBox.Show("校验失败,请检查字符串是否包含特殊字符"); 65 } 66 } 67 68 private void button2_Click(object sender, EventArgs e) 69 { 70 ASCIIEncoding ascii = new ASCIIEncoding(); 71 Byte[] encodedBytes = ascii.GetBytes(textBox1.Text); 72 }