How do I extract bits from 32 bit number

后端 未结 4 1550
小蘑菇
小蘑菇 2020-12-18 12:23

I have do not have much knowledge of C and im stuck with a problem since one of my colleague is on leave.

I have a 32 bit number and i have to extract bits from it.

4条回答
  •  半阙折子戏
    2020-12-18 13:04

    I combined the top 2 answers above to write a C program that extracts the bits for any range of bits (not just 10 through 25) of a 32-bit unsigned int. The way the function works is that it returns bits lo to hi (inclusive) of num.

    #include 
    #include 
    
    unsigned extract(unsigned num, unsigned hi, unsigned lo) {
        uint32_t range = (hi - lo + 1);  //number of bits to be extracted
        //shifting a number by the number of bits it has produces inconsistent 
        //results across machines so we need a special case for extract(num, 31, 0)
        if(range == 32)
            return num;
        uint32_t result = 0;
        //following the rule above, ((1 << x) - 1) << y) makes the mask:
        uint32_t mask = ((1 << range) -1) << lo;
        //AND num and mask to get only the bits in our range
        result = num & mask;
        result = result >> lo; //gets rid of trailing 0s
        return result;
    }
    int main() {
        unsigned int num = 0xd7448eab;
        printf("0x%x\n", extract(num, 10, 25));
    }
    

提交回复
热议问题