Sign extend a nine-bit number in C

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

    This is more of a refinement of previous answers but no fully generic solution has been presented so far. This macro will sign extend a value v with sb indicating the 0-based bit number of the sign bit.

    #define SIGNEX(v, sb) ((v) | (((v) & (1 << (sb))) ? ~((1 << (sb))-1) : 0))
    
    int32_t x;
    
    SIGNEX(x, 15); // Sign bit is bit-15 (16th from the right)
    SIGNEX(x, 23); // Sign bit is bit-23 (24th from the right)
    

    It uses branching to maximize portability across platforms that lack a hardware multiply or barrel shifter.

提交回复
热议问题