Sign extend a nine-bit number in C

前端 未结 7 2035
情话喂你
情话喂你 2020-12-15 05:18

I have a short, instr, that looks like this:

1110xxx111111111

I need to pull out bits 0-9, which I do with (instr &

7条回答
  •  有刺的猬
    2020-12-15 05:49

    (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.

提交回复
热议问题