[英]How to append the bytes of a bit-field to NSMutableData
I have a struct 我有一个结构
typedef struct {
int8_t foo : 1;
} Bar;
I have tried to append the bytes to a NSMutableData object like so: 我试图将字节追加到NSMutableData对象,如下所示:
NSMutableData* data = [[NSMutableData alloc] init];
Bar temp;
temp.foo = 1;
[data appendBytes:&temp.foo length:sizeof(int8_t)];
But I receive an error of Address of bit-field requested. 但是我收到请求的位域地址错误。 How can I append the bytes?
如何追加字节?
Point to the byte, mask the needed bit, and append the variable as a byte: 指向该字节,屏蔽所需的位,然后将变量附加为字节:
typedef struct {
int8_t foo: 1;
} Bar;
NSMutableData* data = [[NSMutableData alloc] init];
Bar temp;
temp.foo = 1;
int8_t *p = (int8_t *)(&temp+0); // Shift to the byte you need
int8_t pureByte = *p & 0x01; // Mask the bit you need
[data appendBytes:&pureByte length:sizeof(int8_t)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.