I am new to Objective-C (and C itself) and should consume NSDatafrom HTTP output. I have never worked with byte arrays or worried about problems with small / large ends, and tried a bit to write the following method for reading NSNumberwith the specified length from this NSData.
- (NSNumber *)readNumberWithLength:(NSUInteger)length
{
Byte k[length];
[data getBytes:k range:NSMakeRange(offset, length)];
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 *dataand NSUInteger offsetare declared as instance variables.
Is this code correct? What should I worry about? I have not tested it on the device itself (only on the simulator), and it seems to work fine for me. Do you have any comments about this?
Thanks!
source
share