Link to home
Start Free TrialLog in
Avatar of zizi21
zizi21

asked on

How to extract the last 20 bits or x bits from an unsigned int (32 bits)

Hi,

say, i have i an unsigned int (32 bits) and i want to extract the last x bits (e.g. the last 20 bits). i found a site that shows how to do the last 8 bits (http://stackoverflow.com/questions/3270307/how-do-i-get-the-lower-8-bits-of-int), but how do i extract the last 20 bits (or some number of bits) ... thanks
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

In exactly the same way.  The 0xFF is the lowest 16 bits which is the same as 0x00FF, so apply a little binary knowledge and the 20 bits should be with 0x07FF
Out of my head (not tested):

unsigned n = ...;
unsigned bitMaskForXBits = 0;
int numberOfBits = 20; // <<<<< Adapt according to your needs
for (int i=0; i<numberOfBits; i++) {
    bitMaskForXBits += (1<<i);
}
unsigned lowXbits = n & bitMaskForXBits;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanx 4 axxepting.
100 points for just repeating me. Good deal. ;-)
@zzynx

We don't know just what the 100pts was for.  Was it for the 0xFFFFF or was it for the principle being the same (a repeat of my first comment - incidentally the very first comment to the question) ?

ps.  Hit the request attention if you are really unhappy, I'll abide by what a moderator decides.
... if you are really unhappy ...
Not "really"
The link actually provides general techniques for any number of bits and how to generate the mask required.  One *could* argue my very first comment saying just use the techniques there is a complete answer (ignoring my cock up with the mask as irrelevant).  I'm not going to argue that, there isn't any point to doing that and I did make a mistake in part of the comment which does spoil it somewhat.

Look.  Both of us provided comments the asker viewed to be useful and did award you 4 times the points as they did me - so it wasn't just give each 250 points to close the question without thinking what is appropriate (or just accepting the final comment even if totally irrelevant and by an expert that didn't contribute anything useful).