Write a program that reverses the order of the bits in an unsigned integer value

+1 vote
asked Apr 4 by Bilal (170 points)
Write a program that reverses the order of the bits in an unsigned integer value. The program should input the value from the user and call function reverse Bits to print the bits in reverse order. Print the value in bits both before and after the bits are reversed to confirm that the bits are reversed properly

output should be this:

please give an integer :2

2=00000000 00000000 00000000 00000010

reverse of this integer:

1073741824 =01000000 00000000 00000000 00000000

2 Answers

0 votes
answered Apr 5 by Luigi Rodorigo (280 points)
There are much efficient ways, of course, but this is quite readable.

#include <stdio.h>
#include <stdint.h>

void print_binary(uint32_t number) {
    
    printf("%d=", number);
    
    for (uint32_t i = 0;i<32;++i) {
        printf("%u", (number>>i) & 1);
    }    
    
    printf("\n");
    
}

uint32_t reverse(uint32_t source) {

    uint32_t result=0;
    
    print_binary(source);
    
    for (uint32_t i = 0;i<32;++i) {
        uint8_t i_bit_value = (source >> i) & 1;
        result |= i_bit_value << (31-i) ;
    }    
    
    print_binary(result);
    
    return result;

}

int main()
{
    
    uint32_t number = 0;
    printf("Enter your number\n");
    if (scanf("%u", &number)==1)
        reverse(number);

}
0 votes
answered Apr 5 by Abir4026 (140 points)
#include <stdio.h>
#include <stdbool.h>
int main()
{
    unsigned int inp_number,rev_number=0,factor=1;
    int i;
    bool inp_number_bits[32];
    printf("enter number:");
    scanf("%d",&inp_number);
    printf("\n%d = ",inp_number);
    for(i=31;i>=0;i--)
    {
        inp_number_bits[i]=(bool)(inp_number & factor);
        inp_number=inp_number>>factor;
        rev_number=((rev_number<<factor)|inp_number_bits[i]);
    }
    for(i=0;i<32;i++)
    {
        printf("%d",(int)inp_number_bits[i]);
        if((i+1)%8==0)
        {
            printf(" ");
        }
    }
    printf("\n");
    printf("reverse of this integer:\n%d = ",rev_number);
    for(i=0;i<32;i++)
    {
        printf("%d",(int)inp_number_bits[31-i]);
        if((i+1)%8==0)
        {
            printf(" ");
        }
    }
    printf("\n");
    return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...