c - 如何用字节数组打包结构
问题描述
我试图打包类似于以下结构的数据。最终这需要是 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]);
}
解决方案
推荐阅读
- c - 需要 Valgrind 输出解释帮助
- c - 为什么在 for 循环中引用全局变量要慢得多?
- c++ - 在 for 循环终止条件中使用 < 或 !=
- go - 在命名接口时,如果结尾与包名相同,是不是一个好名字?
- sas - SAS 平均分组
- labview - 将十进制数字转换为excel字母
- python - 在 node-red python shell 节点窗口中添加虚拟环境路径
- linux - 如何在使用 awk 不匹配时添加行结果“non_assigned”?
- raspberry-pi - 在树莓派上运行 vcpkg 时出现 VCPKG_FORCE_SYSTEM_BINARIES 错误
- python - 将 Shapely STRtree 存储到文件以供重复使用