I have a short, instr
, that looks like this:
1110xxx111111111
I need to pull out bits 0-9, which I do with (instr &
* No branching required *
See http://graphics.stanford.edu/~seander/bithacks.html#FixedSignExtend for a list of very useful bit hacks. Specifically, sign extending a number is as simple as:
/* generate the sign bit mask. 'b' is the extracted number of bits */
int m = 1U << (b - 1);
/* Transform a 'b' bits unsigned number 'x' into a signed number 'r' */
int r = (x ^ m) - m;
You may need to clear the uppermost bits of 'x' if they are not zero ( x = x & ((1U << b) - 1);
) before using the above procedure.
If the number of bits 'b' is known at compile time (e.g., 5 bits in your case) there's even a simpler solution (this might trigger a specific sign-extend instruction if the processor supports it and the compiler is clever enough):
struct {signed int x:5;} s;
r = s.x = x;