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?
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With