开发者

How do I multiply big numbers together in Objective-C?

开发者 https://www.devze.com 2023-03-20 13:27 出处:网络
in Objective-C: unsigned long t1 = 1310789847 * 1000; causes an overflow and shows an incorrect result.

in Objective-C:

unsigned long t1 = 1310789847 * 1000;

causes an overflow and shows an incorrect result.

how do i get 1310开发者_运维技巧789847000?


The result does not fit in a 32 bit unsigned long, so you get an overflow and the result only has the "bottom" 32 bits. You could use unsigned long long instead, which is 64 bit (on the Intel Mac, not sure about other platforms).

unsigned long long t1 = (unsigned long long)1310789847 * 1000;

64 bit integer literals are designated by L, so you could also do:

unsigned long long t1 = 1310789847L * 1000;

Since you are dealing with literals, the above is true. I just found out that for variables, there is no need to cast (Xcode 4):

unsigned long a = 1310789847;
unsigned long b = 1000;
unsigned long long t1 = (unsigned long long)a * b; 
unsigned long long t2 = a * (unsigned long long)b;
unsigned long long t3 = a * b;
unsigned long long t4 = 1310789847 * 1000;
NSLog(@"%lld %lld %lld %lld\n", t1, t2, t3, t4);

The output is:

2011-07-16 08:33:40.445 LongLongTest[16738:903] 1310789847000 1310789847000 1310789847000 824821720

FWIW, I am surprised the compiler notices that the operands must be expanded to 64 bit before doing the multiplication, but can't do the same for literals.


Use NSDecimal. There are all sorts of handy functions in the Foundation framework for manipulating NSDecimal structs, which are basically super large numbers (not just integers). You get the basic operations of add, subtract, multiply, divide, exponentiate, etc, but those are usually powerful enough to do quite a bit of stuff.

0

精彩评论

暂无评论...
验证码 换一张
取 消