I have a short, instr
, that looks like this:
1110xxx111111111
I need to pull out bits 0-9, which I do with (instr &
This is more of a refinement of previous answers but no fully generic solution has been presented so far. This macro will sign extend a value v
with sb
indicating the 0-based bit number of the sign bit.
#define SIGNEX(v, sb) ((v) | (((v) & (1 << (sb))) ? ~((1 << (sb))-1) : 0))
int32_t x;
SIGNEX(x, 15); // Sign bit is bit-15 (16th from the right)
SIGNEX(x, 23); // Sign bit is bit-23 (24th from the right)
It uses branching to maximize portability across platforms that lack a hardware multiply or barrel shifter.