quint64 conversion question
This may be a bit more C++ than Qt but I'm kind of rusty on the casts issues.
I want to write code that would handle large values and wanted to use uint64.
Code:
int myIntVal;
double myDoubleVal;
quint64 myResult = myIntVal * myDoubleVal;
If the result of the multiplication in line 3 is out of the range of int/double would this code work or should I make some modification to assure the value will be correctly stored in the quint64 variable?
Re: quint64 conversion question
The result of the multiplication will probably be an integer before being converted to quint64, so overflow is expected.
The traditional way is to cast the int to double -- and hope that double is big enought for the result...:
quint64 myResult = (quint64)((double)myIntVal * myDoubleVal);
Re: quint64 conversion question
Is there anything more certain I can do in my code to make sure? Hope is nice but...
Re: quint64 conversion question
Make sure your input int and double are either both positive or both negative because your result must be positive.
Re: quint64 conversion question
Thanks for that tip, I since moved to qint64 so won't have that issue, at least.
Re: quint64 conversion question
Don't you get casting errors? Conversion from double to uint looses values. You will definetly loose values anyway, you must use clases that manage large numbers. Also they cannot store infinite amout of data :)
Re: quint64 conversion question
The compiler certainly will not complain about this code as it is because its behaviour is dependent on its run time inputs. The int will be cast to double, multiplied with the other double, and result truncated to store in the qint64. If the range of the input values is known (checked) then there need not be any issue at all with this code. The compiler may warn if you try something like this:
which is detectable at compile time.