How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

前端 未结 8 2340
庸人自扰
庸人自扰 2020-12-02 08:02

Could anyone tell me as to how to extract \'n\' specific bits from a 32-bit unsigned integer in C.

For example, say I want the first 17 bits of the 32-bit value;

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 08:42

    Instead of thinking of it as 'extracting', I like to think of it as 'isolating'. Once the desired bits are isolated, you can do what you will with them.

    To isolate any set of bits, apply an AND mask.

    If you want the last X bits of a value, there is a simple trick that can be used.

    unsigned  mask;
    mask = (1 << X) - 1;
    lastXbits = value & mask;
    

    If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...

    unsigned  mask;
    mask = ((1 << X) - 1) << startBit;
    isolatedXbits = value & mask;
    

    Hope this helps.

提交回复
热议问题