Reputation: 125
I want to compare 2 byte arrays with masking. So I have data and dataTemplate:
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 };
And I have mask:
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 };
All bytes what are 0x00
can be chanaged and 0xFF
cant. So when I compare data and dataTemplate then lets say data[0]
can be 0x3b
in one array and something else in the other. But data[9]
has to be same in both. Right now I'm doing it like this:
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!");
}
}
But this looks like overkill. Maybe there is better ways doing this?
Thanks!
Upvotes: 2
Views: 2161
Reputation: 111810
for (int i = 0; i < data.Length; i++ )
{
if (mask[i] == 0xFF && data[i] != dataTemplate[i]) {
throw new Exception("arrays dont match!");
}
}
Upvotes: 4