Search code examples
bit-manipulationbitwise-operatorsbitbit-shiftbitwise-and

What is the fastest way to check bits in variable using bitwise operations?


For example I have short (2 bytes = 16 bits) variable: (in my project this is sequence of 00, 01 and 10's)

0001010101101001 = 0001.0101|0110.1001

And I want to check if this variable contains sequence of bits, for example I need '01010101' (this is 4 x 01).

What is the fastest way to check this? I found some solutions but I am sure that exists more simple and faster solution.

(pseudocode)
var =  0001010101101001;
need = 0000000001010101;
for(int i=0;i<4;i++)
{
     if(var&need==need)
           return 1;
     else
           var = var >> 2;
}

or:

(pseudocode)
var =   0001010101101001;
need1 = 0000000001010101;
need2 = 0000000101010100;
need3 = 0000010101010000;
need4 = 0001010101000000;
need5 = 0101010100000000;
if(var&need1==need1) return 1;
if(var&need2==need2) return 1;
if(var&need3==need3) return 1;
if(var&need4==need4) return 1;
if(var&need5==need5) return 1;
else return 0;

Solution

  • Your first solution is good:

    for (int Count = 0; Count < 4; Count++)
    {
        if ((Var & Need) == Need)
            Found = true;
        else
            Var = (UInt16)(Var >> 2);   
    }
    

    I actually make things complicated rather than simplifying it.

    This is an alternative solution using masks.

    using System;
    
    public class Program
    {
        public static void Main()
        {
            UInt16 Var = 0x1569;    //0001010101101001 0x1569
            UInt16 Need = 0x5A;     //0000000001011010 0x5A
                                    //0000000001010101 0x55
                                    //0000000001010110 0x56 
            UInt16[] Mask = { 0x00FF, 0x03FC, 0x0FF0, 0x3FC0, 0xFF00 };
    
            bool Found = false;
            for (int Count = 0; Count < 4; Count++)
                Found |= (((Var & Mask[Count]) ^ (Need << (Count + Count))) == 0);
    
            Console.WriteLine(Found);                
        }
    }