Skip to content

Instantly share code, notes, and snippets.

@morgaine
Last active July 16, 2021 22:22
Show Gist options
  • Save morgaine/d67618f50bc20a42dcd49687b64692e6 to your computer and use it in GitHub Desktop.
Save morgaine/d67618f50bc20a42dcd49687b64692e6 to your computer and use it in GitHub Desktop.
Simple gist to illustrate how C bitfields work
/*
* Simple gist to illustrate how C bitfields work.
*/
#include <stdio.h>
struct {
unsigned char bit0 : 1;
unsigned char bit1 : 1;
unsigned char bit2 : 1;
unsigned char bit3 : 1;
unsigned char bit4 : 1;
unsigned char bit5 : 1;
unsigned char bit6 : 1; // 8 1-bit bitfields fit in
unsigned char bit7 : 1; // a single unsigned char.
#ifdef MORE
unsigned char bit8 : 1; // Adding a 9th 1-bit bitfield
// grows the struct to 2 chars.
#endif // MORE
}
bitspace;
int main()
{
printf("Sizeof bitspace = %ld byte(s)\n", sizeof bitspace);
printf(" Bit 3 = %d\n", bitspace.bit3);
printf(" Asserting bit 3\n");
bitspace.bit3 = 1;
printf(" Bit 3 = %d\n", bitspace.bit3);
return 0;
}
CC = gcc
all: bitfields_8 bitfields_9
bitfields_8: bitfields.c
$(CC) bitfields.c -o bitfields_8
bitfields_9: bitfields.c
$(CC) -DMORE=1 bitfields.c -o bitfields_9
run: bitfields_8 bitfields_9
./bitfields_8
./bitfields_9
clean:
rm -f *.o bitfields_[89]
@morgaine
Copy link
Author

morgaine commented Jul 16, 2021

Example build and run:

$ make run

gcc          bitfields.c -o bitfields_8
gcc -DMORE=1 bitfields.c -o bitfields_9

./bitfields_8
Sizeof bitspace = 1 byte(s)
    Bit 3 = 0
    Asserting bit 3
    Bit 3 = 1

./bitfields_9
Sizeof bitspace = 2 byte(s)
    Bit 3 = 0
    Asserting bit 3
    Bit 3 = 1

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