tags:

views:

79

answers:

3

I have a little problem. Essentially, the code:

uint64_t myInteger = 98930 * 98930;
NSLog(@"%qu", myInteger);

...just gets it wrong. I get '1197210308' as the output, which is evidently incorrect. Why is this happening? It can't be that a uint64_t is too small, as they apparently go up to 18 and a half quintillion. Anyone have any idea?

+5  A: 

Try casting the first number so the operation is made using that type:

uint64_t myInteger = (uint64_t)98930 *98930;
Protron
Or: `uint64_t myInteger = 98930UL * 98930UL;`
Paul R
That's it. It works now. Thanks!
Ben Ward
Or even better: UINT64_C(98930) * UINT64_C(98930)
nall
+1  A: 

I don't know much about objective-C, but doing the same in C, integer promotions stop at the integer rank, so you get an integer overflow. Try:

uint64_t myInteger = 98930LLU * 98930;
ninjalj
+4  A: 

98930 is an int, so you're multiplying two ints, which gives an int. You're then assigning to a uint64_t, but it's too late, you've already lost the precision. Make sure one of the operands is of type uint64_t, so the other will be coerced to that type, and the multiplication will be done as uint64_t multiplication.

David Thornley
That explains it well, thanks!
Ben Ward