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 に答える