Using ntohl and htonl problems on iPhone

*爱你&永不变心* 提交于 2019-12-14 03:02:09

问题


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?


回答1:


I have updated the code to use the int32_t and modified the category as follows:

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

The code works correctly now. Awesome thanks.



来源:https://stackoverflow.com/questions/23958827/using-ntohl-and-htonl-problems-on-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!