Created
July 26, 2011 22:12
-
-
Save basus/1108202 to your computer and use it in GitHub Desktop.
Bitfields in C
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
/* Some simple demonstration code to show the use of bit fields in C */ | |
#include <stdio.h> | |
typedef struct { | |
unsigned int s0 : 1; | |
unsigned int s1 : 1; | |
unsigned int s2 : 1; | |
unsigned int s3 : 1; | |
unsigned int s4 : 1; | |
unsigned int s5 : 1; | |
unsigned int s6 : 1; | |
unsigned int s7 : 1; | |
} sensor; | |
/* Simple inline functions to work on the bitfields */ | |
inline void sns_init(sensor *s) | |
{ | |
s->s0 = 0; s->s1 = 0; s->s2 = 0; s->s3 = 0; | |
s->s4 = 0; s->s5 = 0; s->s6 = 0; s->s7 = 0; | |
} | |
inline unsigned int sns_and(sensor s) | |
{ | |
return s.s0 & s.s1 & s.s2 & s.s3 &s.s4 & s.s5 & s.s6 & s.s7; | |
} | |
inline unsigned int sns_or(sensor s) | |
{ | |
return s.s0 | s.s1 | s.s2 | s.s3 |s.s4 | s.s5 | s.s6 | s.s7; | |
} | |
inline void sns_print(sensor s) | |
{ | |
printf("Sensor values are:\n"); | |
printf("%d %d %d %d %d %d %d %d\n", | |
s.s0, s.s1, s.s2, s.s3,s.s4, s.s5, s.s6, s.s7); | |
} | |
int sns_changed(sensor sense, sensor changed) | |
{ | |
/* Has anything changed since initialization? */ | |
if (sns_or(changed)) { | |
printf("Sensor values changed\n"); | |
sns_print(sense); | |
return 1; | |
} else { | |
printf("No sensor values changed\n"); | |
return 0; | |
} | |
} | |
/* A little example */ | |
void main() | |
{ | |
sensor sense; | |
sensor changed; | |
sns_init(&sense); | |
sns_init(&changed); | |
printf("Size of a sensor type is %d\n", sizeof(sensor)); | |
sns_print(sense); | |
/* Let's change something */ | |
sense.s1 = 1; sense.s3 = 1; sense.s6 = 1; | |
changed.s1 = 1; changed.s3 = 1; changed.s6 = 1; | |
if (sns_changed(sense, changed)) { | |
sns_init(&changed); | |
} | |
sense.s2 = 1; sense.s3 = 0; sense.s4 = 1; | |
changed.s2 = 1; changed.s3 = 1; changed.s4 = 1; | |
if (sns_changed(sense, changed)) { | |
sns_init(&changed); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment