deworde deworde - 1 year ago 42
C++ Question

Cleanest way to combine two shorts to an int

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 word, and s2 is the least significant word, and the combined word appears to be signed. (i.e. the top bit of s1 is the sign.)

What is the cleanest way to combine s1 and s2?

I figured something like

const utils::int32 i1 = ((s1<<16) | (s2));

would do, and it seems to work, but I'm worried about left-shifting a short by 16.

Also, I'm interested in the idea of using a union to do the job, any thoughts on whether this is a good or bad idea?

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download