How do I extract bits from 32 bit number

后端 未结 4 1552
小蘑菇
小蘑菇 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 13:15

    OK, here's how I wrote it:

    #include 
    #include 
    
    main() {
        uint32_t in = 0xd7448eab;
        uint16_t out = 0;
    
        out = in >> 10; // Shift right 10 bits
        out &= 0xffff;  // Only lower 16 bits
        printf("%x\n",out);
    }
    

    The in >> 10 shifts the number right 10 bits; the & 0xffff discards all bits except the lower 16 bits.

提交回复
热议问题