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

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

    If you need the X last bits of your integer, use a binary mask :

    unsigned last8bitsvalue=(32 bit integer) & 0xFF
    unsigned last16bitsvalue=(32 bit integer) & 0xFFFF
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题