gpt4 book ai didi

ios - NSData 到 Struct 搞乱数据

转载 作者:行者123 更新时间:2023-11-28 18:20:50 27 4
gpt4 key购买 nike

所以我有 2 个结构,Level 和 Item。当我尝试阅读关卡结构时,一切正常。但是一旦我尝试加载一个项目,我的值(value)观就会变得一团糟。我有这个十六进制值:

    Level-Struct| Item-Struct 
spRot|count | type | anchorX: 25 | anchorY:375 |count
... 00 00 05 00 00 00 19 00 00 00 77 01 00 00 04 00 ...

将数据读入结构后,值是:

type = 0
anchorX = 24576000
anchorY = 262144
pointCount = 0

它似乎用 0 正确地“填充”了类型,但随后继续使用 00 00 77 01(即 24576000)而不是正确的 19 00 00 00 (25)。我怎样才能让我的程序正确读取它?以下是源代码的重要部分:

typedef struct ItemPoint {
SInt32 x;
SInt32 y;
} ItemPoint;

typedef struct Item {
UInt16 type;
UInt32 anchorX;
UInt32 anchorY;
UInt32 pointCount;
ItemPoint *points;
} Item;

typedef struct LevelStruct {
UInt32 width;
UInt32 height;
UInt32 spawnX;
UInt32 spawnY;
UInt16 spawnRot;
UInt16 itemCount;
void *items;
} LevelStruct;



// Test Function

LevelStruct level;
NSUInteger byteOffset = 20;
[data getBytes:&level length:byteOffset];
BlockPolygon *poly = malloc(sizeof(BlockPolygon));
[data getBytes:poly range:NSMakeRange(byteOffset, 14)];

最佳答案

如果你想编码你的结构,你应该将它们声明为打包的并使用 sizeof 而不是魔数(Magic Number)。

typedef struct __attribute__((__packed__)) ItemPoint {
SInt32 x;
SInt32 y;
} ItemPoint;

typedef struct __attribute__((__packed__)) Item {
UInt16 type;
UInt32 anchorX;
UInt32 anchorY;
UInt32 pointCount;
ItemPoint *points;
} Item;

typedef struct __attribute__((__packed__)) LevelStruct {
UInt32 width;
UInt32 height;
UInt32 spawnX;
UInt32 spawnY;
UInt16 spawnRot;
UInt16 itemCount;
void *items;
} LevelStruct;



// Test Function
LevelStruct level;
size_t length = sizeof(LevelStruct);
size_t offset = 0;

[data getBytes:&level length:length];

offset += length;
length = sizeof(BlockPolygon);

BlockPolygon *poly = malloc(length);
[data getBytes:poly range:NSMakeRange(offset, length)];

关于ios - NSData 到 Struct 搞乱数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999273/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com