Question

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* 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?

Was it helpful?

Solution

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)];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top