Question

I have the following linq query in which I am trying to get records from database for a particular id. Then I go through the records and try to find the one in which a bit in one byte is set. But I am getting the error that 'Operator & cannot be applied to byte or bool':

        Byte firstPacketMask = Convert.ToByte("00001000", 2);

        using (aContext _db = new aContext())
         {
             var query = (from data in _db.Datas
                          where data.id == id 
                          orderby data.ServerTime descending //put the last cycle on top of list
                          select data).ToList();

             var mid = query.Where(x => x.Data[0] & firstPacketMask == 16)
                            .FirstOrDefault();

         }

Here Data is a byte array. The first byte of Data has bit fields. I am trying to check if bit 4 is set then I choose that packet.

Was it helpful?

Solution

& has lower precedence than ==, so the compiler parses your expression as x.Data[0] & (firstPacketMask == 16).

Add parentheses to clarify the precedence:

(x.Data[0] & firstPacketMask) == 16

NOTE: It looks like firstPacketMask equals 8, so ANDing it with x.Data[0] will yield 0 or 8, never 16. Perhaps you meant to write

Byte firstPacketMask = Convert.ToByte("00010000", 2);  // bit 4 is set

or maybe just

(x.Data[0] & 16) == 16

OTHER TIPS

What you actually do is checking whether the firstPacketMask is equal to 16 which is not what you intended I think. == operator returns true/false as a result, which then is put against x.Data[0] object, causing the error. As mentioned - take care of correct parenthesis.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top