Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C (iOS) : NSData to long long value?

I'm sending a 8 bytes numeric value over the network (from a c# windows server) that needs to be received by my iDevice. The value is a "long" variable on my server (System.Int64). I checked that the value is correctly converted to a byte array using

byte[] valueBytes = BitConverter.GetBytes(mylongvalue);

The data is received on the iDevice via a NSData variable. I need to skip the first 3 bytes, and then read the 8 next bytes to compute my long long value.

I tried this:

NSData * longlongValueBytes = [receivedData subDataWithRange:NSMakeRange(3,8)];
long long receivedLongLongValue = *(const long long *)[longlongValueBytes bytes];

But this only works for values below 128. Each sent values above or equal to 128 always returns 127 when received.

What am I missing ? Could this be related to a sign problem, or maybe an endianness problem?

Thanks for your help.

like image 663
user1838920 Avatar asked Mar 13 '26 05:03

user1838920


1 Answers

Did you check (using the debugger or some NSLog) the raw content of your NSData to be sure it is received correctly?

Especially check that you don't have different endianness between your different systems (your Windows Server and the iOS device). In general before sending bytes to the network, one try to make sure they are represented in the "network byte order" which corresponds to the "big-endian" order (Most Significant Byte first), regardless of the endianness of the sender or receiver.

You can write NSLog(@"data: %@", longlongValueBytes); in your code to see the hexadecimal representation of your data and check that you received the expected bytes.

Then to convert those bytes into a long long, try this instead of your code:

unsigned long long receivedLongLongValue = 0;
[longlongValueBytes getBytes:&receivedLongLongValue length:8];
NSLog(@"received long value: %llu", receivedLongLongValue);
like image 113
AliSoftware Avatar answered Mar 14 '26 22:03

AliSoftware



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!