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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With