Compare byte arrays with masking

纵饮孤独 提交于 2019-12-11 11:09:44

问题


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!


回答1:


    for (int i = 0; i < data.Length; i++ )
    {
        if (mask[i] == 0xFF && data[i] != dataTemplate[i]) {
            throw new Exception("arrays dont match!");
        }
    }


来源:https://stackoverflow.com/questions/5251355/compare-byte-arrays-with-masking

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!