温馨提示×

C语言reverse二进制位的实现

小樊
93
2024-06-24 09:37:22
栏目: 编程语言

#include <stdio.h>

unsigned int reverseBits(unsigned int num) {
    unsigned int count = sizeof(num) * 8 - 1;
    unsigned int reverse_num = num;
    
    num >>= 1;
    while (num) {
        reverse_num <<= 1;
        reverse_num |= num & 1;
        num >>= 1;
        count--;
    }

    reverse_num <<= count;
    return reverse_num;
}

int main() {
    unsigned int num = 10; // 00000000000000000000000000001010
    unsigned int reversed_num = reverseBits(num);

    printf("Original number: %u\n", num);
    printf("Reversed number: %u\n", reversed_num);

    return 0;
}

这段代码实现了一个函数reverseBits,用于将一个无符号整数中的二进制位逆序。在main函数中,我们定义了一个初始值为10的无符号整数,将其二进制位翻转后输出。

0