Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you are doing is only meaningful if the shorts and the int are all unsigned. If either of the shorts is signed and has a negative value, the idea of combining them into a single int is meaningless, unless you have been provided with a domain-specific specification to cover such an eventuality.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...