简体   繁体   English

有符号整数要无符号并返回?

[英]Signed integer to unsigned and back?

I would like to store a signed int32 into an unsigned uint32 such that I can extract a int32 from it later. 我想将一个有符号的int32存储到一个无符号的uint32 ,以便以后可以从中提取一个int32 The value of the uint32 itself isn't used when it stores an integer like this, but I can't use a union in this case unfortunately. uint32本身的值在存储这样的整数时不使用,但不幸的是,在这种情况下我不能使用联合。 The way I currently do this is by simply converting it: 我目前这样做的方法是简单地将其转换:

int32  signedVar   = -500;
uint32 unsignedVar = uint32(signedVar);
func(int32(unsignedVar)); // should supply the function with -500

This appears to work, but I'm afraid it might not be portable, and that there might be needless conversions happening behind the scenes for what I'm hoping is a no-op. 这似乎可行,但恐怕它可能无法移植,并且由于我希望没有操作,幕后可能会发生不必要的转换。

Is -500 or any other negative number guaranteed to survive this conversion? 是否可以保证-500或其他任何负数都能在此转换后继续存在? If not, is there a "painless" (none of the types are changed, only the conversion method) alternative? 如果不是,是否有“无痛”(所有类型都没有改变,只有转换方法)替代?

Edit: I'm most concerned with making sure the value in int32 is preserved in a uint32 so it can be used as a int32 of the same value later, the uint32 version is never used. 编辑:我最关心确保int32的值保留在uint32以便以后可以将其用作相同值的int32 ,而从未使用过uint32版本。 (editing because SO asked me to explain how this isn't a duplicate of another question; it doesn't specify what the results of the conversion should look like, or that it needs to be symmetrical like this, making it too general to be applied here) (进行编辑是因为SO要求我解释这不是另一个问题的重复;它没有指定转换结果应该是什么样,或者它必须像这样对称,因此太笼统了。在这里应用)

If your machine uses 1s-complement or sign-magnitude arithmetic (which is allowed by the C standard at least; not sure about C++), then this double conversion will convert the value -0 into 0. If your machine uses 2s complement, then this will be fine. 如果您的计算机使用1s补码或符号幅度算法(至少C标准允许;不确定C ++),则此双转换会将值-0转换为0。如果您的计算机使用2s补码,则很好

That said, I'm not aware of any machine built in the last 30 years that uses anything other than 2s complement for arithmetic. 就是说,我不知道过去30年中制造的任何机器都使用2s补码以外的东西进行算术运算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM