在iPhone上使用ntohl和htonl问题

时间:2014-05-30 16:04:15

标签: ios objective-c htonl

我有一个NSDATA对象,我创建然后通过网络发送。我无法从收到的NSDATA流中获取正确的值。

这是一些重现我的问题的快速代码。无需网络传输。

    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);

我正在使用NSDATA类别来简化流程。这是类别代码:

    @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

woaInt8AtOffset运行良好,显示4& 6. woaInt32AtOffset显示一些巨大的数字。

代码有什么问题?

1 个答案:

答案 0 :(得分:1)

我已更新代码以使用int32_t并修改了类别,如下所示:

- (int)woaInt32AtOffset:(size_t)offset
{
    int32_t buf;
    [self getBytes:&buf range:NSMakeRange(offset, 4)];
    return ntohl(buf);
}

代码现在正常运行。非常感谢。