我想将 2 字节数组与掩码进行比较。所以我有数据和数据模板:
byte[] data = new byte[] { 0x3b, 0xfe, 0x18, 0x00, 0x00, 0x80, 0x31, 0xfe,
0x45, 0x45, 0x73, 0x74, 0x75, 0x49, 0x44, 0x20,
0x76, 0x65, 0x72, 0x20, 0x31, 0x2e, 0x30, 0xa8 };
byte[] dataTemplate = new byte[] { 0x66, 0xfe, 0x18, 0x00, 0x00, 0x80, 0x31, 0xfe,
0x45, 0x45, 0x73, 0x74, 0x75, 0x49, 0x44, 0x20,
0x76, 0x65, 0x72, 0x20, 0x31, 0x2e, 0x30, 0xa8 };
我有面具:
byte[] mask = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 };
所有字节都0x00
可以更改并且0xFF
无法更改。因此,当我比较 data 和 dataTemplate 时,可以说data[0]
可以0x3b
在一个数组中,而在另一个数组中。但data[9]
两者必须相同。现在我正在这样做:
List<byte> maskedDataList = new List<byte>();
for (int i = 0; i < data.Length; i++ )
{
byte maskedByte = (byte)((dataTemplate[i] & mask[i]));
atrList.Add(maskedByte);
}
for (int i = 0; i < data.Length; i++)
{
if ((data[i] & maskedDataList[i]) != MaskedDataList[i])
{
throw new Exception("arrays dont match!");
}
}
但这看起来有点矫枉过正。也许有更好的方法来做到这一点?
谢谢!