Read NSNumber from NSData

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!

以上就是Read NSNumber from NSData的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏