Anne Quinn
Anne Quinn

Reputation: 13002

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. 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. 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? 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. (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)

Upvotes: 1

Views: 764

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126175

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.

That said, I'm not aware of any machine built in the last 30 years that uses anything other than 2s complement for arithmetic.

Upvotes: 2

Related Questions