Question

For example:

  1. INT64_MIN to 0
  2. 0 to INT64_MAX+1
  3. INT64_MAX to UINT64_MAX

Below is my code:

uint64_t int64ToUint64(int64_t value)
{
    uint64_t uvalue = value - std::numeric_limits<int64_t>::min();
    return uvalue;
}

It works, but there is signed integer overflow, and per C++ standard, signed integer overflow is behavior undefined. Any other solutions without integer overflow?

Était-ce utile?

La solution

Since conversion from signed to unsigned types is well defined and since there's no overflow on unsigned arithmetic, you can do what you want safely by first converting the signed value to an unsigned type:

uint64_t int64ToUint64(int64_t value)
{
    uint64_t uvalue = value;

    uvalue += INT64_MAX;
    uvalue += 1;

    return uvalue;
}

Autres conseils

uint64_t int64ToUint64(int64_t value){
    uint64_t res = *(reinterpret_cast<uint64_t*>(&value));
    return res ^ numeric_limits<int64_t>::min();
}
int64_t uint64ToInt64(uint64_t value){
    value ^= numeric_limits<int64_t>::min();
    return *(reinterpret_cast<int64_t*>(&value));
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top