Skip to content

Instantly share code, notes, and snippets.

@DinkDonk
Last active October 22, 2022 15:48
Show Gist options
  • Select an option

  • Save DinkDonk/166f8f978b88ecbaf72494a5a48c6390 to your computer and use it in GitHub Desktop.

Select an option

Save DinkDonk/166f8f978b88ecbaf72494a5a48c6390 to your computer and use it in GitHub Desktop.
uint8_t to bit-field in C
#include <stdio.h>
#include <stdint.h>
typedef union {
uint8_t value;
struct {
unsigned flag0:1;
unsigned flag1:1;
unsigned flag2:1;
unsigned flag3:1;
unsigned flag4:1;
unsigned flag5:1;
unsigned flag6:1;
unsigned flag7:1;
} flags;
} Register;
int main() {
Register my_reg;
my_reg.value = 0b00000001;
if (reg.flags.flag0) {
printf("Flag 0 = true\n");
} else {
printf("Flag 0 = false\n");
}
return 0;
}
@DinkDonk
Copy link
Author

DinkDonk commented Oct 21, 2022

Handy approach when you want to give more structure to registers. Especially when dealing with registers read from I2C or SPI devices.
Initialize the Register union by its value and query the flags struct after that. The value is eg. the raw byte you get from the I2C device.
Define Register unions for each register type you want to deal with and rename the flags to something meaningful.

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