Skip to content

Instantly share code, notes, and snippets.

@ryesalvador
Created June 1, 2016 03:13
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 ryesalvador/398061c31a299bcc2deb6a7fc605ac60 to your computer and use it in GitHub Desktop.
Save ryesalvador/398061c31a299bcc2deb6a7fc605ac60 to your computer and use it in GitHub Desktop.
Using bitfields in storing struct members in C
#include <stdio.h>
/* A field for storing yes or no; uses 1 bit of storage. */
typedef struct {
unsigned int food:1;
unsigned int metal_music:1;
unsigned int dressy_clothes:1;
unsigned int football:1;
} likes;
/* Prototype for the function to display likes. */
void display(char *message, likes truth);
int main(void)
{
/* Set the values; A value of 0 for false and 1 for true. */
likes me = {1,1,0,1};
likes dad = {1,0,1,1};
/* Bitwise operation AND of each element of the struct. */
likes agree = {me.food & dad.food,
me.metal_music & dad.metal_music,
me.dressy_clothes & dad.dressy_clothes,
me.football & dad.football};
/* Bitwise operation XOR of each element of the struct. */
likes disagree = {me.food ^ dad.food,
me.metal_music ^ dad.metal_music,
me.dressy_clothes ^ dad.dressy_clothes,
me.football ^ dad.football};
display("Things we both like\n", agree);
display("Things that we disagree on\n", disagree);
return 0;
}
void display(char *message, likes truth) {
puts(message);
printf("Food: %s\n", truth.food ? "yes" : "no");
printf("Heavy metal music: %s\n", truth.metal_music ? "yes" : "no");
printf("Wearing dressy clothes: %s\n", truth.dressy_clothes ? "yes" : "no");
printf("Football: %s\n", truth.football ? "yes" : "no");
puts("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment