Cleanest way to combine two shorts to an int

后端 未结 7 1367
野的像风
野的像风 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:46

    You want to cast data.first to an int32 before you do the shift, otherwise the shift will overflow the storage before it gets a chance to be automatically promoted when it is assigned to combined data.

    Try:

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

    This is of course assuming that data.first and data.second are types that are guaranteed to be precisely 16 bits long, otherwise you have bigger problems.

    I really don't understand your statement "if data.second gets too big, the | won't take account of the fact that they're both shorts."

    Edit: And Neil is absolutely right about signedness.

提交回复
热议问题