30分 |
void Main() { byte[] data = { 0x00, 0x08, 0x0E, 0x32, 0x30 }; byte[] bs1 = new byte[160]; data.CopyTo(bs1, 0); byte[] bs2 = new byte[160]; data.CopyTo(bs2, 0); bs2[0] = 0x01; bool ok1 = Check(bs1, bs2); // true bs2[0] = 0x03; bool ok2 = Check(bs1, bs2); // false } static bool Check(byte[] bs1, byte[] bs2, int tolerance = 1) { if (bs1.Length != bs2.Length) return false; Func<byte, int> countBit = b => { return Enumerable.Range(0, 8).Sum(i => (b & (1 << i)) > 0 ? 1 : 0); }; int errorCount = bs1.Zip(bs2, (x, y) => (byte)(x ^ y)).Sum(b => countBit(b)); return errorCount <= tolerance; } |
30分 |
^符号在C#中为XOR,中文为‘异或’,XOR两个bit,当他们不相等就得到1:
1 ^ 1 = 0 0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 因此,把两个字节串进行异或,并统计bit==1的数量,就得到误码的数量。 |
20分 |
转换成十进制整数,如
Convert.ToInt16(“FF”, 16) Convert.ToInt32(“FF”, 16) 异或后转乘二进制表示,并删除 “0”,统计“1”的个数。如 |
20分 |
var a = "00 08 0E 32 30"; var b = "01 08 0E 32 30"; var a1 = a.Split(new char[1]{"" ""}); var b1 = b.Split(new char[1]{"" ""}); var sum = 0; for(int i=0; i<a1.Count(); i++) { sum += Convert.ToString(Convert.ToInt32(a1[i], 16) ^ Convert.ToInt32(b1[i], 16), 2).Replace("0", "").Count(); } Console.WriteLine(sum); |