Kenneth Brody wrote On 04/14/06 12:58,:
Ben Pfaff wrote:
"HARDCORECODER" <do*************@gmail.com> writes:
ok I want to extract the first 4 bits of a 32 bit interger. The SIZE
doesn't really matter. 8,16, 0r 32. I want the first 4 bits.....bit
0,1,2 and,3. I want to exract these and place into another variable.
myvar & 0xf will do that, given your apparent definition of "first".
here is my Idea
int bits1to3=(x>>1)&0x0f; // bits 1 2 3 4
That "works" is you have 5-bit ints.
or
long bits1to3=(x>>12)&0x0f; // bits 12 13 14 15
And 16-bit longs.
to extract bit field I should shift right then use a bit mask
containing all ones. This will store the first 4 bits into bits1to3
right?
I don't see why you want to do a shift if you want the
least-significant 4 bits.
I don't think ke doesn't want the least-significant bits -- it sounds
more like he wants the most-significant bits. (At least, that's what
it appears he wants. Maybe. Perhaps.)
Or, maybe he's not sure what he wants.
How about something like:
( foo >> ( (sizeof(foo) * CHAR_BITS) - 4 ) ) & 0x0f
Am I correct that "sizeof(foo)*CHAR_BITS" gives you the number of bits
in "foo"?
It does, but there are two nagging difficulties.
- If `foo' has padding bits, bits that are part of its
representation but not part of its value, you'll be shifting
by too many places. This seems to be mostly a "theoretical"
concern, as C implementations where integer types have padding
bits are about as rare as snowballs in Hell. Still, the
Standard permits the peculiar practice, and if such a machine
is ever built Murphy's Law ensures that your code will try to
run on it.
- If `foo' is a signed type with a negative value, the
effect of right-shifting is undefined. It may or may not
be possible to shift the sign bit into a value position and
then isolate it with an AND; the results simply aren't
predictable. This is one of the reasons why scarred veterans
(where do you think the scars came from?) recommend using
unsigned types for bit-walloping.
--
Er*********@sun.com