I am a student and I am writing a function in C to sign extend a given bit field. I\'m working with 32 bits.
I looked this answer up on Google but didn\'t find what I w
As I understand it, you want to pluck N arbitrary bits (N >= 1 & <=32) from a bit stream in a 32-bit variable and represent them as a 2's complement number (presumably returning that number as a signed int 32).
What this says is that you take the selected bits, place them in the low-order (ie, right) end of a work variable, and then "extend" the left-most selected bit by propagating (copying) it leftward through the remaining (previously undefined) bits in the work variable. This can be done as a single consistent algorithm, with no need to special-case any particular value of N.
For two bits it will produce the possible values 1, 0, -1, and -2 (for bit patterns 01, 00, 11, and 10 respectively). For one bit it will produce the possible values 0 and -1 (for bit patterns 0 and 1 respectively).