720 views
1 votes
1 votes

As an illustration of some of the bit operators, consider the function getbits(x,p,n) that returns the (right adjusted) n-bit field of x that begins at position p. We assume that bit position 0 is at the right end and that n and p are sensible positive values. For example, getbits(x,4,3) returns the three bits in positions 4, 3 and 2, right-adjusted.

Code:

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

The expression x >> (p+1-n) moves the desired field to the right end of the word. ~0 is all 1-bits; shifting it left n positions with ~0<<n places zeros in the rightmost n bits; complementing that with ~ makes a mask with ones in the rightmost n bits.

Can anyone please explain this to me??

What's happening here???

1 Answer

0 votes
0 votes

getbits(x,p,n) works like get n bit field of x from position p 

Consider getbits(4,3,2) 

Here, x = 4, p = 3 and n = 2

It is also mentioned that bit position 0 is at the right end.

x = 0000 0100 

So, by definition it should return 2 bits value from position 3 i.e. 01 whose value is 1.

Now, let's perform 

return (x >> (p+1-n)) & ~(~0 << n);

p + 1 - n = 3 + 1 - 2 = 2

So, x is right shifted by 2. Hence x becomes 0000 0001     ....(1)

~0 = 1111 1111 is left shifted by n i.e. 2

(~0 << n) = 1111 1100

and finally ~(~0 << n) = 0000 0011   ....(2)

Performing AND operation of (1) and (2) , we get 0000 0001 whose value is 1.

Basically ~(~0 << n) is acting like a mask of all 1's to get the right adjusted n bit field from position p of x. 

Related questions

0 votes
0 votes
0 answers
2
Surya Dhanraj asked Aug 18, 2017
171 views
The bitwise AND operator & is often used to mask off some set of bits, for example,n = n & 0177sets to zero all but the low order 7 bits of n.Can anyone please explain ho...
0 votes
0 votes
0 answers
3
Surya Dhanraj asked Aug 18, 2017
119 views
The bitwise or operator is used to turn bits on.What is the meaning of turning bits on??Is it mean making it one.And what will be the definition of turning bits off??Some...
1 votes
1 votes
0 answers
4