Sign extend a nine-bit number in C

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 0x1F0x10 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).

Leave a Comment