I have an array of ushorts and want to iterate over the array and check if the first two bits of that ushort are 11 if so I want to clear them. However the bit mask I am using to read the first two bits in my conditional are not working properly and the if statement does not trigger when the first two bits are 11
static public void trimData(ushort[] rawData)
{
for(int i = 0; i < rawData.Length; i++)
{
if (((ushort)(rawData[i] & (1 << 15)) == 1) && ((ushort)(rawData[i] & (1 << 14)) == 1))
{
rawData[i] = (ushort)(rawData[i]&~(1<<15));
rawData[i] = (ushort)(rawData[i]&~(1<<14));
}
}
}
How can I use bitmasks to do this correctly?
You can shift these bits to have them being the rightmost ones and then mask with 0b11:
To clear these bits you use XOR
^(since1 ^ 1 == 0):Let's combine these parts:
Finally, the method can be