Cleanest way to combine two shorts to an int

后端 未结 7 1364
野的像风
野的像风 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-18 00:05

    Using a union to do the job looks like a good choice, but is a portability issue due to endian differences of processors. It's doable, but you need to be prepared to modify your union based on the target architecture. Bit shifting is portable, but please write a function/method to do it for you. Inline if you like.

    As to the signedness of the shorts, for this type of operation, it's the meaning that matters not the data type. In other words, if s1 and s2 are meant to be interpreted as two halves of a 32 bit word, having bit 15 set only matters if you do something that would cause s2 to be sign extended. See Mark Ransoms answer, which might be better as

    inline utils::int32 CombineWord16toLong32(utils::int16 s1, utils::int16 s2)
    {
        return ((s1 <<16) | (s2 & 0xffff));
    }
    

提交回复
热议问题