Search code examples
ccpu-worduint32uint16

Extract upper and lower word of an unsigned 32-bit integer


To extract the upper and lower word of an unsigned 32-bit integer and store each one in separate uint16_t-variables I do as follows (nbr is an unsigned 32-bit integer):

uint16_t lower_word = (uint16_t) nbr & 0x0000FFFF;  // mask desired word
uint16_t upper_word = (uint16_t) ((nbr & 0xFFFF0000) >> 16); // right-shift after masking

Is the explicit conversion to an uint16_t unnecessary? What other more effective ways, if there are any, do you recommend to obtain the desired results instead of this approach?


Solution

  • uint16_t lower_word = (uint16_t) nbr;
    uint16_t upper_word = (uint16_t) (nbr  >> 16);
    

    masks are useless

    cast are necessary else the compiler could produce warning

    {edit to take into account the remark of Lundin / Eric Postpischil}

    for instance gcc -Wconversion produces a warning without the cast