Last active
July 16, 2021 22:22
-
-
Save morgaine/d67618f50bc20a42dcd49687b64692e6 to your computer and use it in GitHub Desktop.
Simple gist to illustrate how C bitfields work
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example build and run: