Answer the question
In order to leave comments, you need to log in
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.
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question