Bitwise Flag Manager
C
Easy
2 views
Problem Description
8 boolean flags can be stored in a single char variable using bitwise operators. Create Functions: setFlag(), clearFlag(), toggleFlag(), checkFlag().
Official Solution
#include <stdio.h>
#include <stdbool.h>
/* Set the flag at position pos (0-7) */
void setFlag(unsigned char *flags, int pos) {
*flags |= (1 << pos);
}
/* Clear the flag at position pos (0-7) */
void clearFlag(unsigned char *flags, int pos) {
*flags &= ~(1 << pos);
}
/* Toggle the flag at position pos (0-7) */
void toggleFlag(unsigned char *flags, int pos) {
*flags ^= (1 << pos);
}
/* Check the flag at position pos (0-7), returns true or false */
bool checkFlag(unsigned char flags, int pos) {
return (flags & (1 << pos)) != 0;
}
/* Print all flags for demonstration */
void printFlags(unsigned char flags) {
printf("Flags: ");
for (int i = 7; i >= 0; i--) {
printf("%d", checkFlag(flags, i) ? 1 : 0);
}
printf("n");
}
int main() {
unsigned char flags = 0; // All flags are 0 initially
printf("Initial state:n");
printFlags(flags);
printf("nSetting flags 0, 3, 5:n");
setFlag(&flags, 0);
setFlag(&flags, 3);
setFlag(&flags, 5);
printFlags(flags);
printf("nClearing flag 3:n");
clearFlag(&flags, 3);
printFlags(flags);
printf("nToggling flag 5 and 7:n");
toggleFlag(&flags, 5);
toggleFlag(&flags, 7);
printFlags(flags);
printf("nChecking flags individually:n");
for (int i = 0; i < 8; i++) {
printf("Flag %d: %sn", i, checkFlag(flags, i) ? "ON" : "OFF");
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!