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

前端 未结 8 2352
庸人自扰
庸人自扰 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:30

    Modulus works to get bottom bits (only), although I think value & 0x1ffff expresses "take the bottom 17 bits" more directly than value % 131072, and so is easier to understand as doing that.

    The top 17 bits of a 32-bit unsigned value would be value & 0xffff8000 (if you want them still in their positions at the top), or value >> 15 if you want the top 17 bits of the value in the bottom 17 bits of the result.

提交回复
热议问题