C ++ how to find out if a 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 the number N ends with B

where N is any number and B is also any number

eg,

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 

:)

+4
source share
4 answers

In 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 
+3
source

If you know the number of bits in B, you need to build a template with as many bits as 1. Suppose int has 32 bits in 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 calculate the number of bits in B via:

 int tmpB = B; int numberOfBitsInB = 0; while (tmpB) { numberOfBitsInB++; tmpB >>= 1; } 
+1
source
 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 calculate the number of bits in B.

0
source

You can create a mask for any length of the bit pattern. Here is an example of C. This would prevent you from doing hard 0x7 encoding if you want to check for more than three bits.

 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"); } 
0
source

Source: https://habr.com/ru/post/1346226/


All Articles