I have an NSDATA object which I create and then send over the network. I have having trouble getting the correct values out of the received NSDATA stream.
Here is some quick code to reproduce my problem. No network transmission required.
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:150];
// put data in the array
[data woaAppendInt8:4];
[data woaAppendInt32:2525];
[data woaAppendInt8:6];
[data woaAppendInt32:1616];
// get data out of array
size_t offset = 0;
int x1 = [data woaInt8AtOffset:offset];
offset += 1; // move to next spot
NSLog(@"Should be 4 = %i",x1);
int x2 = [data woaInt32AtOffset:offset];
offset = offset + 4; // Int's are 4 bytes
NSLog(@"Should be 2525 = %i",x2);
int x3 = [data woaInt8AtOffset:offset];
offset += 1; // move to next spot
NSLog(@"Should be 6 = %i",x3);
int x4 = [data woaInt32AtOffset:offset];
offset = offset + 4; // Int's are 4 bytes
NSLog(@"Should be 1616 = %i",x4);
I am using NSDATA categories to make the process easier. Here is the category code:
@implementation NSData (woaAdditions)
- (int)woaInt32AtOffset:(size_t)offset
{
const int *intBytes = (const int *)[self bytes];
return ntohl(intBytes[offset / 4]);
}
- (char)woaInt8AtOffset:(size_t)offset
{
const char *charBytes = (const char *)[self bytes];
return charBytes[offset];
}
@end
@implementation NSMutableData (waoAdditions)
- (void)woaAppendInt32:(int)value
{
value = htonl(value);
[self appendBytes:&value length:4];
}
- (void)woaAppendInt8:(char)value
{
[self appendBytes:&value length:1];
}
@end
The woaInt8AtOffset works great and displays the 4 & 6. The woaInt32AtOffset displays some HUGE number.
What is the problem with the code?