0

我有一个 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 显示一些巨大的数字。

代码有什么问题?

4

1 回答 1

1

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

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

该代码现在可以正常工作。太好了,谢谢。

于 2014-05-30T17:50:58.473 回答