Cleanest way to combine two shorts to an int

后端 未结 7 1365
野的像风
野的像风 2020-12-17 23:31

I have two 16-bit shorts (s1 and s2), and I\'m trying to combine them into a single 32-bit integer (i1). According to the spec I\'m dealing with, s1 is the most significant

7条回答
  •  天涯浪人
    2020-12-17 23:59

    What you've got looks nearly correct, but will probably fail if the second part is negative; the implicit conversion to int will probably sign-extend and fill the upper 16 bits with ones. A cast to unsigned short would probably prevent that from happening, but the best way to be sure is to mask off the bits.

    const utils::int32 combineddata = ((data.first<<16) | ((data.second) & 0xffff));
    

提交回复
热议问题