What happens to this reverse bit order function?

I am ashamed to admit that I do not know as much about bits and bit manipulations as I probably should. I tried to fix this this weekend by writing a few "reverse bit orders" and "counting bit bits." I gave an example from here , but when I implemented it as shown below, I found that I needed to loop while <29. If I loop while <32 (as in the example) Then, when I try to print an integer (using written by my printBits function), I seem to be missing the first 3 bits. It makes no sense to me, can someone help me?

Thanks for the help, I added comments to show the changes I made.

int reverse(int n)
{
    int r = 0;
    int i = 0;
    for(i = 0; i < 29; i++) //Should be i < 32
    {
        r = (r << 1) + (n & 1); //| instead of + to make it obvious I'm handling bits
        n >>=1;
    }

    return r;
}

Here is my printBits function:

void printBits(int n)
{
    int mask = 0X10000000; //unsigned int mask = 0X80000000;
    while (mask)
    {
        if (mask & n)
        {
            printf("1");
        }
        else
        {
            printf("0");
        }
        mask >>= 1;
    }
    printf("\n");
}

?

int reverse2(int n)
{
    int r = n;
    int s = sizeof(n) * 7; // int s = (sizeof(n) * 8) -1

    for (n >>= 1; n; n >>=1)
    {
        r <<=1;
        r |= n & 1;
        s--;


    r <<= s;
    return r;
}
+3
5

:

int mask = 0x10000000;

. , , () , int.

:

unsigned int mask = 0x80000000;

0x80000000 , . . .

+3
int mask = 0X10000000;

1 28. 0X80000000.

+5

, 0x80000000 0x10000000.

>>> bin (0x80000000)  
'0b10000000000000000000000000000000'  
>>> bin (0x10000000)  
'0b10000000000000000000000000000'

. 0x1... .

+3

Instead +you should use |(bitwise or). And you must use < 32.

+2
source

As written, this will change the bottom 29 bits of n to r. The first three bits of n will be left at n (shifted down 29 bits) and will not be returned.

I would suspect a problem with your printBits function if you see something else.

change

The printBits function prints the lower 29 bits of n, so it all makes sense.

+1
source

Source: https://habr.com/ru/post/1742604/


All Articles