C - 如何检查 8 位是否在 32 位中?
C - How to check if 8 bits are in 32 bit?
我想检查 char
中的 8 位是否是 int
中 32 位的子串。
a = 0110 1010 1011 0100 0000 0110 1010 0010 (32 bit int)
b = 0100 0000 (8 bit char)
is_in(a, b) --> true
这是我的代码:
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;
我希望它更有效率。
有什么想法吗?
嗯,你可以试试...
bool is_in(uint32_t a, uint8_t b) {
while (a >= b) {
if ((a & 0xff) == b) return true;
a >>= 1;
}
return false;
}
我想检查 char
中的 8 位是否是 int
中 32 位的子串。
a = 0110 1010 1011 0100 0000 0110 1010 0010 (32 bit int)
b = 0100 0000 (8 bit char)
is_in(a, b) --> true
这是我的代码:
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;
我希望它更有效率。 有什么想法吗?
嗯,你可以试试...
bool is_in(uint32_t a, uint8_t b) {
while (a >= b) {
if ((a & 0xff) == b) return true;
a >>= 1;
}
return false;
}