Search code examples
objective-cnsdatabit-fieldsnsmutabledata

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


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)];