PDA

View Full Version : quint64 conversion question



frankiefrank
20th November 2011, 11:20
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.



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?

mvuori
20th November 2011, 14:25
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);

frankiefrank
20th November 2011, 21:59
Is there anything more certain I can do in my code to make sure? Hope is nice but...

ChrisW67
21st November 2011, 00:12
Make sure your input int and double are either both positive or both negative because your result must be positive.

frankiefrank
28th November 2011, 20:54
Thanks for that tip, I since moved to qint64 so won't have that issue, at least.

bu7ch3r
29th November 2011, 14:52
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 :)

ChrisW67
30th November 2011, 09:10
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:


int a(1e45);

which is detectable at compile time.