Home > Software design >  Why wont my C code about reversed bits work?
Why wont my C code about reversed bits work?

Time:11-14

I am working on code to reverse an unsigned int whose bits are the same but in reverse order. My code wont stop running while taking user input. What am I doing wrong?

#include <stdio.h>

unsigned int reverse_bits(unsigned int n);

int main(void) {
        unsigned int n;
        printf("Enter an unsigned integer: ");
        scanf("%u",&n);
        printf("%u\n",reverse_bits(n));
        return 0;
}

unsigned int reverse_bits(unsigned int n) {
        unsigned int reverse = 0;
        while(n>0) {
                reverse <<= 1;
                if((n & 1) == 1) {
                        reverse = reverse^1;
                }
        }
        return reverse;
}

CodePudding user response:

as @Mark Benningfield said you forget to modify n inside the loop and the

best way to reverse a string is:-

It only runs upto when the leftmost bit is 1.

  unsigned int reverse_bits(unsigned int n) 
    {
        int reverse = 0;
        int x = 1;
        while ( n > 0 )
        {
            reverse = reverse << 1;
            if ( n & x )
                reverese = reverse | 1;
            n = n >> 1;
        }
        return reverse;

CodePudding user response:

In your program, the while condition is checking whether n is greater than zero. However, inside the loop, there was no operation that modifies the n. So please try using this. It will work.

unsigned int reverse_bits(unsigned int n) {
    unsigned int reverse = 0;
    while (n>0) {
            reverse <<=1;
            if((n & 1) == 1) {
                    reverse = reverse | 1;
            }
            n=n>>1;

    }
    return reverse;

}

  • Related