On Wed, 12 Apr 2006 22:52:04 -0700, HARDCORECODER wrote:
ok here is the question. I want to exract the first 4 bits in a int so
let say
int b = somenumber;
int result= 0;
result = b << 4;
if I got this right result should contain the 4 bits that were shifter to
the left right? :) and if I'm wrong how can i get an x number of bits into
a variable?
"first four bits" is ambiguous...and depends upon whether your system is
big or little endian...and as everyone knows, little endian machines suck!
but, to answer your question, shift left increases the value by a power
of two and shift right decreases by a power of two....so, to extract bit
fields out of a number with bits numbers 2^n n=[0..15] use
bits1to3=(x>>1) &0x0f; // bits 1 2 3 4
bits12to15=(x>> 12)&0x0f; // bits 12 13 14 15
to extract bit fields you should shift right then use a bit mask
containing all ones.