简体   繁体   中英

C++ how to know if number ends with some bit pattern

I want to know if a number ends with some predefined bit patterns.

for example i want to know if a number N end with B

where, N is any number and B is also any number

for example

if N = 01011100 
  B = 100 then this C++ function should return 1 here in this case 1

if N = 01011100
  B = 101 then this function should return 0

:)

For the first case:

unsigned n = 0x5C;
unsigned m = 0x7; // "mask"
unsigned b = 0x4;
if ((n & m)==b) {
  ...do something...
}

Here's how it works:

01011100  n
00000111  m
00000100  n & m  (bitand operator)
00000100  b

If you know number of bits in B, then you need to build a pattern with this number of bits as 1. Supposing int has 32 bits on your system:

unsigned int mask = 0xFFFFFFFF >> (32 - numberOfBitsInB);
if (N & mask == B)
    printf("%d ends with %d\n", N, B);
else
  printf("Nope");

You can also compute number of bits in B via:

int tmpB = B;
int numberOfBitsInB = 0;
while (tmpB)
{
    numberOfBitsInB++;
    tmpB >>= 1;
}
unsigned int mask = ~0 >> (sizeof(unsigned int) * 8 - num_bits_in_B);

if (N & Bitmask == B)
  printf("%d ends with %d\n", N, B);
else
  printf("Nope");

Use the method suggested by @Benoit above to compute the number of bits in B.

It is possible to generate a mask for any length bit pattern. Here is a C example. This would prevent you from having to hardcode 0x7 if you would like to check for more than 3 bits matching.

bool bitPattern(int N, int B)
{
    int shift = 0;
    int mask = 0x0;
    while(B >> shift++ > 0) mask |= 0x01 << shift-1;
    return  (N & mask) == B;
}

int main(int argc, char *argv[]) {

    printf("01011100 ends with 100 ? %s\n", bitPattern(0x5C, 0x04) ? "Yes" : "No");
    printf("01011100 ends with 101 ? %s\n", bitPattern(0x5C, 0x05) ? "Yes" : "No");
}

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