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

  • A+
Category:Languages

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?

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: