1

我有一个结构

typedef struct {
   int8_t foo        : 1;
} Bar;

我试图将字节附加到 NSMutableData 对象,如下所示:

NSMutableData* data = [[NSMutableData alloc] init];
Bar temp;
temp.foo = 1;
[data appendBytes:&temp.foo length:sizeof(int8_t)];

但我收到请求的位域地址错误。如何附加字节?

4

1 回答 1

1

指向字节,屏蔽所需位,并将变量附加为字节:

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)];
于 2011-09-01T20:45:44.147 回答