如何用字节数组打包结构

时间:2019-08-26 14:26:03

标签: c arrays struct pack

我正在尝试打包类似于以下结构的数据。 最终,该类型必须为NSData

typedef struct __attribute__((packed)) {
    UInt8  a;
    UInt8  b;
    UInt8  c[17];
} myStruct;

如果我尝试以下操作,将值分配给c时会出错。

myStruct str = {};
str.a = 1;
str.c = aByteArray; // `Array UInt8 [17] is not assignable.`

如何通过为myStruct分配值或使用output构造等效数据来打包数据?     我认为以下实现适用于前2个八位位组,但不适用于17 UInt8's的最后一个数组,后者也需要填充后2个八位位组。一个问题似乎是Im并未在单个数组中实际分配最后的17个八位位组,因此解析器不会成功。

UInt8 a = 1;
UInt8 b = 0b00001111;

UInt8 output[] = {};
int idx = 0;
output[idx++] = a;
output[idx++] = b;
// add each
for (int i=0; i<15; i++) {
    // otherByteArray == UInt[15]
    output[idx++] = otherByteArray[i];
}
UInt8 padding = 0xAA;
output[idx++] = padding;
output[idx++] = padding;

更新 该实现似乎可行,除了在第8个索引之后不匹配byteArrays时应该匹配之外(填充除外)。

    // Unpack
    Packet *packet = (Packet *)request.value.bytes;
    if (packet) {
        UInt8  a = packet->a;
        UInt8  b = packet->b;
        UInt8 *c = packet->c;

        for (int i=0; i<15; i++) {
            NSLog(@"c[%d]: %hhu", i, c[i]);
        }

        // Pack
        UInt8 output[20] = {};
        NSUInteger idx = 0;
        // packet num
        UInt8 a = a + 1;
        memcpy(&output[idx], &a, sizeof a);
        idx += sizeof a;
        // b
        UInt8 b = 0b01001111;
        memcpy(&output[idx], &b, sizeof b);
        idx += sizeof b;

        // c
        UInt8 result[17] = {};
        for (int i=0; i<15; i++) {
            result[i] = c[i];
        }
        UInt8 padding = 0xAA;
        result[15] = padding;
        result[16] = padding;
        memcpy(&output[idx], &result, sizeof result);
        idx += sizeof result;

        NSData *outputData = [NSData dataWithBytes:&output length:idx];

        ResponsePacket *response = (ResponsePacket *)outputData.bytes;
        UInt8 *responseC = response->c;

        for (int i=0; I<17; i++) {
            NSLog(@"responseC[%d]: %hhu", i, responseC[i]);
        }

0 个答案:

没有答案
相关问题