了解字节顺序和函数,如CFSwapInt32HostToBig

时间:2010-06-16 07:06:07

标签: c objective-c

我的游戏中有一个枚举。带有附加PacketType的简单字符串消息与GameKit WIFI连接一起发送消息(因此它知道如何处理消息)。我使用Apple的GKRocket示例代码作为起点。

代码本身的运作非常出色;我只是想了解CFSwapInt32HostToBig的行是什么。 这到底是做什么用的?为什么需要这样做?我的猜测是它确保PacketType值可以转换为无符号整数,这样它就可以可靠地发送它,但这对我来说听起来并不正确。< / p>

文档说明“将32位整数从big-endian格式转换为主机的本机字节顺序。”但我真的不明白这意味着什么。

typedef enum {
    PacketTypeStart,         // packet to notify games to start
    PacketTypeRequestSetup,  // server wants client info
    PacketTypeSetup,         // send client info to server
    PacketTypeSetupComplete, // round trip made for completion
    PacketTypeTurn,          // packet to notify game that a turn is up
    PacketTypeRoll,          // packet to send roll to players 
    PacketTypeEnd            // packet to end game
} PacketType; 

// ....

- (void)sendPacket:(NSData *)data ofType:(PacketType)type
{
    NSLog(@"sendPacket:ofType(%d)", type);
    // create the data with enough space for a uint
    NSMutableData *newPacket = [NSMutableData dataWithCapacity:([data length]+sizeof(uint32_t))];
    // Data is prefixed with the PacketType so the peer knows what to do with it.
    uint32_t swappedType = CFSwapInt32HostToBig((uint32_t)type);
    // add uint to data
    [newPacket appendBytes:&swappedType length:sizeof(uint32_t)];
    // add the rest of the data
    [newPacket appendData:data];

    // Send data checking for success or failure
    NSError *error;
    BOOL didSend = [_gkSession sendDataToAllPeers:newPacket withDataMode:GKSendDataReliable error:&error];
    if (!didSend)
    {
        NSLog(@"error in sendDataToPeers: %@", [error localizedDescription]);
    }
}

1 个答案:

答案 0 :(得分:3)

网络数据是大端。客户端可能是大端(例如PowerPC Mac)或小端(例如x86 Mac)。因此,您的代码确保在小端平台(例如x86)上处理字节序 - 当然,它在大端系统上是无操作的。