Last active
October 22, 2022 15:48
-
-
Save DinkDonk/166f8f978b88ecbaf72494a5a48c6390 to your computer and use it in GitHub Desktop.
uint8_t to bit-field in C
This file contains hidden or 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
| #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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Handy approach when you want to give more structure to registers. Especially when dealing with registers read from I2C or SPI devices.
Initialize the
Registerunion by itsvalueand query theflagsstruct after that. The value is eg. the raw byte you get from the I2C device.Define
Registerunions for each register type you want to deal with and rename the flags to something meaningful.