Skip to content

Instantly share code, notes, and snippets.

@0xPIT
Created October 31, 2014 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xPIT/7dd7f043dc55a0a097b3 to your computer and use it in GitHub Desktop.
Save 0xPIT/7dd7f043dc55a0a097b3 to your computer and use it in GitHub Desktop.
Bit Fields in Gcc: Don't forget to pack!
#include <stdio.h>
typedef struct bits_packed {
unsigned int b0:1;
unsigned int b1:1;
unsigned int b2:1;
unsigned int b3:1;
unsigned int b4:1;
unsigned int b5:1;
unsigned int b6:1;
unsigned int b7:1;
} __attribute__((packed)) Bits_t;
typedef struct bits_unpacked {
unsigned int b0:1;
unsigned int b1:1;
unsigned int b2:1;
unsigned int b3:1;
unsigned int b4:1;
unsigned int b5:1;
unsigned int b6:1;
unsigned int b7:1;
} Bits_u_t;
int main() {
Bits_t bits;
Bits_u_t bits_u;
printf("bits: %lu, bits_u: %lu\n", sizeof(bits), sizeof(bits_u));
}
@0xPIT
Copy link
Author

0xPIT commented Oct 31, 2014

gcc test.bit.c && ./a.out
bits: 1, bits_u: 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment