I'm trying to process a byte array retrieving from a sensor. In the retrieved byte array, there will be a byte-mask, xx-xx-xx-xx, that tells me which data will be in the array.
The sensor mask:
DATA_1 0x00000001
DATA_2 0x00000002
DATA_3 0x00000004
DATA_4 0x00000008
DATA_5 0x00000010
DATA_6 0x00000020
DATA_7 0x00000040
DATA_8 0x00000080
DATA_9 0x00000100
DATA_10 0x00000200
DATA_11 0x00000400
This byte-mask 43-05-00-00, for example, tells me that data_1, data_2, data_7, data_9, data_11 will be in response array. I know this by using bitwise-and in Calculator app of Windows: in hex mode, type 543, click "And" button, then type the sensor mask (1, 2, 4, 8, 10,...). If the result is the same as sensor mask (1, 2, 4, 8, 10,...), this data is included. But I don't know how to achieve this in C#.
This is my ideal but it gave me error: Operator '&' cannot be applied to operands of type 'byte[]' and 'byte[]'
int[] sensorMaskList = new int[length] {1, 2, 4, 8,... };
internal List<int> GetSelectedData(byte[] byteMask)
{
List<int> lstDataIndex = new List<int>();
for (int i = 0; i < sensorMaskList.Length; i++)
{
byte[] mask = BitConverter.GetBytes(sensorMaskList[i]);
if (mask & byteMask == mask)
lstDataIndex.Add(i);
}
return lstDataIndex;
}
Can someone give me some ideal. Thanks in advance and sorry for bad english
You can use BitArray
class to easily perform and operation
int[] sensorMaskList = new int[length] {1, 2, 4, 8,... };
internal List<int> GetSelectedData(byte[] byteMask)
{
BitArray byteMaskBits = new BitArray(byteMask);
List<int> lstDataIndex = new List<int>();
for (int i = 0; i < sensorMaskList.Length; i++)
{
byte[] mask = BitConverter.GetBytes(sensorMaskList[i]);
BitArray maskBits = new BitArray(mask);
if(maskBits.And(byteMaskBits) == maskBits)
{
lstDataIndex.Add(i);
}
}
return lstDataIndex;
}