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

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

    This is a briefer variation of the accepted answer: the function below extracts the bits from-to inclusive by creating a bitmask. After applying an AND logic over the original number the result is shifted so the function returns just the extracted bits. Skipped index/integrity checks for clarity.

    uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to) 
    {
      unsigned mask = ( (1<<(to-from+1))-1) << from;
      return (orig16BitWord & mask) >> from;
    }
    

提交回复
热议问题