rplankenhorn
rplankenhorn

Reputation: 2084

Objective C - NSNumber storing and retrieving longLongValue always prefixes with 0xFFFFFFFF

I am trying to store a file size in bytes as an NSNumber. I am reading the file download size from the NSURLResponse and that gives me a long long value and I then create an NSNumber object from that value and store it. When I go to retrieve that value later, it comes back with all the higher bytes set as FFFFFFFF.

For example, I read in the size as 2196772870 bytes (0x82f01806) and then store it into the NSNumber. When I get it back, I get -2098194426 bytes (0xffffffff82f01806). I tried doing a binary AND with 0x00000000FFFFFFFF before storing the value in NSNumber but it still comes back as negative. Code below:

long long bytesTotal = response.expectedContentLength;
NSLog(@"bytesTotal = %llx",bytesTotal);
[downloadInfo setFileTotalSize:[NSNumber numberWithInt:bytesTotal]];
//[downloadInfo setFileTotalSize:[NSNumber numberWithLongLong:bytesTotal]];
long long fileTotalSize = [[downloadInfo fileTotalSize] longLongValue];        
NSLog(@"fileTotalSize = %llx",fileTotalSize);

Output:

bytesTotal = 82f01806
fileTotalSize = ffffffff82f01806

Any suggestions?

Edit: Completely forgot the setter for the downloadInfo object.

Upvotes: 0

Views: 372

Answers (1)

progrmr
progrmr

Reputation: 77191

The problem is this line:

[downloadInfo setFileTotalSize:[NSNumber numberWithInt:bytesTotal]];

bytesTotal is not an int, it's a long long, so you should be using numberWithLongLong:, not numberWithInt:. Change it to:

[downloadInfo setFileTotalSize:[NSNumber numberWithLongLong:bytesTotal]];

The conversion is causing it to be sign extended to 64 bits, and the number starting with 8 appears to be a negative number so that bit gets extended all the way thru the upper long, causing it to be ffffffff.

Upvotes: 1

Related Questions