Hi,
I pretty new to Objective-C (and C itself) and need to consume a NSData
from a HTTP output. I've never really worked with byte arrays or had to worry about little/big endian issues, and have struggled a bit to write the following method to read a NSNumber
with a specified length from that NSData
.
- (NSNumber *)readNumberWithLength:(NSUInteger)length
{
Byte k[length];
[data getBytes:k range:NSMakeRange(offset, length)]; // big endian byte array representing a number
offset += length;
NSNumber *number;
if (length==4) {
number = [NSNumber numberWithUnsignedInt:CFSwapInt32BigToHost(*(uint32_t *)k)];
} else if (length==2) {
number = [NSNumber numberWithUnsignedShort:CFSwapInt16BigToHost(*(uint16_t *)k)];
} else if (length==1) {
number = [NSNumber numberWithUnsignedChar:*(uint8_t *)k];
} else if (length==8) {
number = [NSNumber numberWithUnsignedLongLong:CFSwapInt64BigToHost(*(uint64_t *)k)];
} else {
number = [NSNumber numberWithInt:0];
}
return number;
}
I have NSData *data
and NSUInteger offset
declared as instance variables.
Is this code correct? Is there anything I should worry about? I haven't tested it on an actual device yet (only on the Simulator) and it seems to be working fine for me. Do you have any comments on it?
Thank you!