我实现了一个函数,可以反转数字中的位。要反转的数中的位数可以变化。然而,当然,如果它不能被 4 整除,它必须在末尾向左移动以与半字节对齐。这就是我所拥有的:
uint64_t revBits(uint64_t num)
{
unsigned int counter = 0;
uint64_t reverse_num = 0;
while (num)
{
reverse_num <<= 1;
reverse_num |= num & 1;
num >>= 1;
counter++;
}
if (counter % 4 != 0)
{
reverse_num <<= (4 - counter % 4);
}
return reverse_num;
}
是的,这有效。但是,有没有一种更干净的方法可以在最后执行此操作,而不是检查是否
(counter % 4 != 0)
?就像单行解决方案一样,根据数字 % 4 进行移位,而不先检查它是否为 0?
以 4 位为一组进行反转?
类似:
#include <stdint.h>
#include <stdio.h>
uint64_t revBits(uint64_t num) {
unsigned int counter = 0;
uint64_t reverse_num = 0;
while (num) {
reverse_num <<= 1;
reverse_num |= num & 1;
num >>= 1;
counter++;
}
if (counter % 4 != 0) {
reverse_num <<= (4 - counter % 4);
}
return reverse_num;
}
uint64_t revBits4(uint64_t num) {
unsigned reverse_table[] = {0b0000, 0b1000, 0b0100, 0b1100,
0b0010, 0b1010, 0b0110, 0b1110,
0b0001, 0b1001, 0b0101, 0b1101,
0b0011, 0b1011, 0b0111, 0b1111};
uint64_t reverse_num = 0;
while (num) {
reverse_num <<= 4;
reverse_num |= reverse_table[num & 0b1111];
num >>= 4;
}
return reverse_num;
}
int main(void) {
for (int k = 0; k < 2000000000; k += 1083) {
uint64_t v1, v2;
v1 = revBits(k);
v2 = revBits4(k);
if (v1 != v2) printf("Oops ... revBits4() failed for %d\n", k);
}
}