问题描述
我有两个16位短裤(s1和s2),并且我试图将它们组合成一个32位整数(i1)。根据我处理的规范,s1是最高有效词,s2是最低有效词,并且组合的词似乎是带符号的。 (即s1的最高位是符号。)
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.)
将s1和s2组合在一起的最干净方法是什么?
What is the cleanest way to combine s1 and s2?
我发现类似
const utils::int32 i1 = ((s1<<16) | (s2));
可以,而且似乎可行,但我担心向左移动短距离16。
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?
推荐答案
仅在短裤和int都未签名的情况下,您所做的事情才有意义。如果任何一条短裤均已签名且具有负值,则除非将其提供给特定领域的规范来涵盖此类可能性,否则将它们组合为单个int的想法是没有意义的。
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.
这篇关于将两个短裤组合成一个整数的最干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!