I've been working with C++ and have been utilizing the UBA sanitizer to convert a double to an unsigned long long. However, I've been encountering an issue when the value is negative, which results in the error message: "runtime error: value -2 is outside the range of representable values of type 'long long unsigned int'"
The code is something like this:
unsigned long long valueULL = 0;
double value = -2;
valueULL = (unsigned long long)value;
I tried to use this cast instead and it doesn't help:
valueULL = std::make_unsigned_t<unsigned long long>(value);
Is there a way to cast it without encountering this error?
It seems that you're referring to clang's
-fsanitize=undefinedUBSanitizer. The sanitizer is correct in this case, and your code really does contain undefined behavior:- [conv.fpint] §1
You can fix your undefined behavior with a two-step cast:
Or alternatively, you could call
std::llround:Note: this will produce a very great value, namely
ULLONG_MAX - 2. If this is what you actually want, then these solutions make sense. Otherwise, you should listen to the sanitizer and make sure that yourdoubledoesn't turn negative before converting tounsignedtypes.