Joh*_*hny 7 c int bit-manipulation char bitwise-operators
我想检查a char中的8位是否是32位的子串int.
a = 0110 1010 1011 0100 0000 0110 1010 0010 (32 bit int)
b = 0100 0000 (8 bit char)
is_in(a, b) --> true
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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;
Run Code Online (Sandbox Code Playgroud)
我希望它更有效率.任何的想法?
好吧,你可以试试......
bool is_in(uint32_t a, uint8_t b) {
while (a >= b) {
if ((a & 0xff) == b) return true;
a >>= 1;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)