简体   繁体   中英

Quickest way to check for (different) set bits in more integers

If I want to check if a specific bit is set, then a simple and quick code (in my opinion) is

bool setbit(int number, int position)
{ 
  return ((number) & (1 << position)) != 0
}

Now what if I had two integers and wanted to check 2 bits in each of them (the 4 positions will always be different)? The function should return true if all of them are set on the specified positions.

Is there a better way than calling the shown function 4 times?

The general way to check that all bits given in a mask are set in a number is:

(number & mask) == mask

In this case the mask would be made by setting the bits at the given positions:

int mask = (1 << pos1) | (1 << pos2) | (1 << pos3) | (1 << pos4);

In total,

bool test4Bits(int number, int pos1, int pos2, int pos3, int pos4)
{
    int mask = (1 << pos1) | (1 << pos2) | (1 << pos3) | (1 << pos4);
    return (number & mask) == mask;
}

A more flexible version of harolds answer

Usage

BitsAreSet(0b10011001, 0, 3, 4, 7); // check 4 bits
BitsAreSet(0b10011001, 0); // check only 1 bit

Implementation

public static bool BitsAreSet(int number, params int[] bitPositions)
{
      var mask = 0;

      foreach (var bitPosition in bitPositions)
          mask |= (1 << bitPosition);

      return (number & mask) == mask;
}

Extension method version

I had to add this, because I am a fan of extension methods.

Usage

0b10011010.BitsAreSet(0, 3, 4, 7)

Implementation

public static bool BitsAreSet(this int number, params int[] bitPositions)
{
    var mask = 0;

    foreach (var bitPosition in bitPositions)
        mask |= (1 << bitPosition);

    return (number & mask) == mask;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM