Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - How to check if 8 bits are in 32 bit?

I want to check if the 8 bits in a char are a substring of the 32 bits of an int.

a = 0110 1010 1011 0100 0000 0110 1010 0010 (32 bit int)
b = 0100 0000 (8 bit char)

is_in(a, b) --> true

Here is my code:

    for (int i = 0; i < 25; i++) {
       int tmp = a;
       tmp <<= 24;
       tmp >>= 24;
       int res = b ^ tmp;
       res <<= 24;
       res >>= 24;
       if (res == 0)
          return 1;
       else
          a >>= 1;
    }
    return 0;

I want it more efficient. Any idea?

like image 515
Johny Avatar asked Nov 02 '15 12:11

Johny


People also ask

How do you check if a bit is on or off in C?

Bitwise AND Operator (&) is used to check whether a bit is SET (HIGH) or not SET (LOW) in C and C++ programming language. Bitwise AND Operator (&) is a binary operator, which operates on two operands and checks the bits, it returns 1, if both bits are SET (HIGH) else returns 0.

How do you know if two bits are set?

Check if a number has two adjacent set bits in C++ Suppose the number 12 has two consecutive 1s (12 = 1100). To check this type of number, the idea is very simple. We will shift the number 1 bit, then do bitwise AND. If the bitwise AND result is non-zero, then there must be some consecutive 1s.

How do you know if a single bit is set?

In gcc, you can use __builtin_popcount() , to find the count of set bits in any number. Then check if count is equal to 1 or not.


1 Answers

Well, you could try...

bool is_in(uint32_t a, uint8_t b) {
  while (a >= b) {
    if ((a & 0xff) == b) return true;
    a >>= 1;
  }
  return false;
}
like image 162
flaviodesousa Avatar answered Sep 18 '22 18:09

flaviodesousa