complex bitwise operation

I am reading the following example from the book:

1
2
3
4
5
6
7
8
/* getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n)
{
    return (x >> (p+1-n)) & ~(~0 << n);
}

// usage:
getbits(x,4,3)


So let's say x is unsigned integer 100. The binary form is 1100100. p is the start position. n I think is the number of bits to return to caller function. So we start at position 4 in above example, we add 1 and subtract 3 (which is n). Hence, we shift x 2 places to the right. This trims the 2 0s on the right. So now we are left with 0011001. And so this expression "(x >> (p+1-n))" evaluates to 0011001. Now we evaluate second parenthesis. We use the one's complement of 0, which is 1. So the binary representation is 00000001. And then we shift that value by 3 to produce 00001000. Then we take the one's complement of that value to get 11110111. Then we use bitwise AND with our two return values of the two expression to get 00110001. Is this interpretation right? And if so, I don't see how this is a solution of getting 3 bits from position 4.

~0 is not 1, try printing it out
I just printed it out on my computer:

1
2
3
4
5
6
7
8
9
10
$ cat example.c
#include <stdio.h>

int main(void)
{
    printf("The value is %u\n",~0);
    return 0;
}
$ ./example
The value is 4294967295


Why is the value 4294967295?

When I convert that number to binary I get:
11111111111111111111111111111111

Is that because this is a 32 bit processor?

So basically 0 is equivalent to 00000000000000000000000000000000?
The type of the expression 0 is int, which is indeed 32 bit on almost every modern compiler.
Last edited on
Topic archived. No new replies allowed.