I have a short, instr
, that looks like this:
1110xxx111111111
I need to pull out bits 0-9, which I do with (instr &
(instr & 0x1FF) * (1 - ((unsigned short)(instr & 0x100) >> 7))
How does it work? It selects your sign bit and shifts it to the 2's position. This is used to generate either the value 1 (if your sign bit was absent) or -1 (if your sign bit was present).
This solution is branchless and does not depend on undefined behavior.