Sign extend a nine-bit number in C

前端 未结 7 2078
情话喂你
情话喂你 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:54

    Assuming a short is 16 bits:

    You can do it manually: (instr & 0x1FF) | ((instr & 0x100) ? 0xFE00 : 0). This tests the sign bit (the uppermost bit you are retaining, 0x100) and sets all the bits above it if the sign bit is set. You can extend this to 5 bits by adapting the masks to 0x1F, 0x10 and 0xFFE0, being the lower 5 bits, the 5th bit itself and all the bits 5-16 respectively.

    Or you can find some excuse to assign the bits to the upper part of a signed short and shift them down (getting a sign-extension in the process): short x = (instr & 0x1FF) << 7; x >>= 7; The latter may actually end up being more straightforward in assembly and will not involve a branch. If instr is signed this can be done in a single expression: (instr & 0x1FF) << 7 >> 7. Since that already removes the upper bits it simplifies to instr << 7 >> 7. Replace 7 with 11 for 5 bits (16-5).

提交回复
热议问题