Consider the following code:
#include <cstdint>
#include <iostream>
#include <iomanip>
int main()
{
auto x=std::uint32_t(1)<<31;
std::cout << " x: 0x" << std::hex << x << " = " << std::dec << x << "\n";
int32_t sx=x;
std::cout << "sx: 0x" << std::hex << sx << " = " << std::dec << sx << "\n";
}
I get the following output from it:
x: 0x80000000 = 2147483648
sx: 0x80000000 = -2147483648
Here the value of x
can't be represented in int32_t
, and the C++11 Standard says the following about this conversion:
If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.
Is this still implementation-defined even with intXX_t
, for which we have certain guarantees on representation?
If yes, then how can I guarantee that the result will be as shown above? Should I memcpy
my unsigned value to signed to get two's complement interpretation, or is there a more straightforward way?