Sign extend a nine-bit number in C

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

    * No branching required *

    See http://graphics.stanford.edu/~seander/bithacks.html#FixedSignExtend for a list of very useful bit hacks. Specifically, sign extending a number is as simple as:

    /* generate the sign bit mask. 'b' is the extracted number of bits */
    int m = 1U << (b - 1);  
    
    /* Transform a 'b' bits unsigned number 'x' into a signed number 'r' */
    int r = (x ^ m) - m; 
    

    You may need to clear the uppermost bits of 'x' if they are not zero ( x = x & ((1U << b) - 1); ) before using the above procedure.

    If the number of bits 'b' is known at compile time (e.g., 5 bits in your case) there's even a simpler solution (this might trigger a specific sign-extend instruction if the processor supports it and the compiler is clever enough):

    struct {signed int x:5;} s;
    r = s.x = x;
    

提交回复
热议问题