Reputation:
Consider the following integer:
uint32_t p = 0xdeadbeef;
I want to get:
p & ((1 << 4) - 1);
and that went good.however, for 4..7 what I tried did not go as expected:
(p >> 16) & 0xFFFF0000
Why would it not extract the bits I want? Am I not moving p
16 positions to the right and then taking out 4 bits?
Would really appreciate an answer with explanation, thanks!
Upvotes: 0
Views: 155
Reputation: 43558
If you want to get bits from 4..7
(p>>4) & 0xf
If you want to get bits from N
to (N+4-1)
(p>>N) & 0xf
And N
should be <32 (if your system is 32 bits system). otherwise you will get undefined behaviour
Upvotes: 1
Reputation: 958
No, you're actually removing bits 0 to 15 from p, so it will hold 0xdead and afterwards you perform the bitwise and so this will yield 0.
If you want to extract the upper 16 bits you will first have to the & operation and shift afterwards:
p = (p & 0xffff0000) >> 16;
To extracts the bits 4 to 7 you will want to do:
p = p & 0xf0;
or if you want them shifted down
p = (p & 0xf0) >> 4;
Btw. Could it be that mean the term nibble 4 to 7 instead of bit 4..7? Nibbles are 4 bits and represented by one hex digit, this would correlate with what you are trying to in the code
Upvotes: 1