Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing long long argument in Objective-C?

I am trying to pass a long long type as an argument to a function and failing. I can assign 5000000000 to a long long variable as follows:

long long value = 5000000000;

But when I try to pass that variable into a method:

- (void)viewDidLoad
{
    [super viewDidLoad];

    long long value = 5000000000;

    [self test:value];
}

-(void) test:(long long)value
{
    printf("%d\n", value);
}

The value is printed as 705032704 and not 5000000000. I verified this in the debugger. The 705032704 value is constant so it seems like some kind of truncation is happening.

I'm about to start pulling my hair out with this one. Can anyone help?

Thanks, Alan

like image 987
Alan Spark Avatar asked Jan 24 '26 07:01

Alan Spark


2 Answers

Your printf is trying to print it as a signed int instead of long long.

Use %lld for long long

like image 51
Kal Avatar answered Jan 26 '26 21:01

Kal


Try this:

printf("%lld\n", value);

The problem with your code is that %d assumes that the argument being printed there will be an integer. printf will therefore look only at a few bytes of your number, not the entire number, and what it sees there is equivalent to 705032704 in binary.

You can verify this yourself: 5000000000 in binary is as follows (byte boundaries are marked by |):

1|00101010|00000101|11110010|00000000

In Objective C, integers are stored on 4 bytes, so Objective C looks at the last 4 bytes, which is exactly equal to 705032704. (Note that 705032704 = 5000000000 - 232, which accounts for the last bit in the leftmost byte that is lost).

like image 30
Tamás Avatar answered Jan 26 '26 23:01

Tamás