问题
Im trying to pack data that resembles the following struct. Ultimately this needs to be of type NSData
.
typedef struct __attribute__((packed)) {
UInt8 a;
UInt8 b;
UInt8 c[17];
} myStruct;
If I try the following I get an error when assigning value to c
.
myStruct str = {};
str.a = 1;
str.c = aByteArray; // `Array UInt8 [17] is not assignable.`
How can pack data by either assigning values to myStruct
or constructing its equivalent using output
?
I think the following implementation would work for first 2 octets, but not the last array of 17 UInt8's
, that also needs padding for last 2 octets. One problem looks like Im not actually assigning last 17 octets in a single array, so parser wouldn't succeed.
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;
Update This implementation seems to work, except the byteArrays do not match after the 8th index.. when they should, except for the padding.
// 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]);
}
来源:https://stackoverflow.com/questions/57659851/how-to-pack-struct-with-a-byte-array