Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast unsigned to signed and back

I have an unsigned value that needs to pass through a function as a signed value (it is not touched by the function). When it comes out I cast it back to unsigned. I know that the result of a cast to signed is implementation defined when overflowing, but can I at least guarantee that I end up with the same value when I cast it back (like with function pointers)?

Example:

int32_t function_with_default(int32_t a_Default)
{
    // Try some stuff
    // ...

    // Fall back to default
    return a_Default;
}

void main()
{
    uint32_t input = UINT32_MAX;
    uint32_t output = static_cast<uint32_t>(function_with_default(static_cast<int32_t>(input));

    // Is is guarenteed to be true?
    input == output;
}

I do have the guarentee that the signed integer is always bigger or equal than the unsigned integer in bytes, so no data should be lost due to lack of space.

like image 669
Rick de Water Avatar asked Dec 09 '16 10:12

Rick de Water


1 Answers

No, you don't have such guarantee: [conv.integral]

2 If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

3 If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.

like image 132
alexeykuzmin0 Avatar answered Nov 16 '22 21:11

alexeykuzmin0