Qualcomm Interview Question

How would you obtain n bits from position p in an integer?

Interview Answers

Anonymous

Feb 23, 2011

First left shift 32-p bits followed by 32-n bits right shift.

Anonymous

Jul 2, 2011

/* getbits: get n bits from position p */ unsigned getbits(unsigned x, int p, int n) { return (x >> (p+1-n)) & ~(~0 >(p+1-n) moves the desired field to the right end of the word. ~0 is all 1 bits; shifting it left n bit positions with ~0 << n places zeros in the rightmost n bits; complementing that with ~ makes a mask with ones in the rightmost n bits. Directly from K&R