首页 > 解决方案 > 如何用字节数组打包结构

问题描述

我试图打包类似于以下结构的数据。最终这需要是 type 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 个八位字节进行填充。一个问题看起来像我实际上并没有在一个数组中分配最后 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;

更新 这个实现似乎有效,除了 byteArrays 在第 8 个索引之后不匹配。当它们应该匹配时,除了填充。

    // 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]);
        }

标签: carraysstructpack

解决方案


推荐阅读