Skip to content

Instantly share code, notes, and snippets.

@agagniere
Last active January 11, 2023 14:28
Show Gist options
  • Save agagniere/9d4547c13950b4cfcc6fede76e4f51b5 to your computer and use it in GitHub Desktop.
Save agagniere/9d4547c13950b4cfcc6fede76e4f51b5 to your computer and use it in GitHub Desktop.
Demonstrate bitfields
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#define EPOLLIN 1
#define EPOLLOUT 4
struct simple
{
bool read;
bool write;
};
struct bitfields
{
bool read : 1;
bool write : 1;
};
struct adhoc
{
bool read : 1;
bool _ : 1;
bool write : 1;
};
#define EVAL(expr) #expr, expr
#define EVAL_PP(expr) #expr, EVAL(expr)
int main()
{
printf("%-30s: %zu\n", EVAL(sizeof(struct simple)));
printf("%-30s: %zu\n", EVAL(sizeof(struct bitfields)));
printf("%-30s: %zu\n", EVAL(sizeof(struct adhoc)));
struct adhoc read_and_write = {.read = true, .write = true};
printf("%-22s= %s = %" PRIu8 "\n", EVAL_PP(EPOLLIN | EPOLLOUT));
printf("%-30s= %" PRIu8 "\n", EVAL(read_and_write));
}
@agagniere
Copy link
Author

agagniere commented Jan 10, 2023

$ make demo_bitfields && ./demo_bitfields 
cc     demo_bitfields.c   -o demo_bitfields
sizeof(struct simple)         : 2
sizeof(struct bitfields)      : 1
sizeof(struct adhoc)          : 1
EPOLLIN | EPOLLOUT    = 1 | 4 = 5
read_and_write                = 5

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