I
I
IndusDev2017-11-04 20:42:02
C++ / C#
IndusDev, 2017-11-04 20:42:02

Bit operations K&R?

To illustrate some bitwise operations, consider the function getbits(x, p, n), which
forms a field of n bits cut from x, starting at position p, pressing it to the right edge.
Bit 0 is assumed to be the rightmost bit, and n and p are meaningful positive numbers.
For example, getbits(x, 4, 3) will return the 4th, 3rd, and 2nd bits of x,
right-aligned. Here's the function:
/* getbits: get n bits starting at position p */
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p+1-n)) & ~(~ 0 << n);
}
The expression x >> (p + 1-n) shifts the field we need to the right edge.

Fragment from the book K&R. Actually, it is with bit operations in this book that I have problems. Apparently, it is assumed here that you already have knowledge about them ...
Well, in general, it is not clear where (p + 1-n) came from, how to get this expression?
+ What does "starting from position p" mean? Is the position counted from the right edge, assuming the rightmost bit is at position 0?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-11-04
@zagayevskiy

The position is considered from the left, 31,30,...,2,1,0. It turned out because that is the number of bits that must be shifted in order to press it to the right edge.
For example, getbits(x, 4, 3) will return the 4th, 3rd, and 2nd bits of x,
right-aligned.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question