C
Bit Operations
Set, clear, toggle, and test bits with bitwise operators and flags.
By EZ4Code Team
bitflagsbitwise
Code
#include <stdio.h>
#include <stdint.h>
int main(void) {
uint32_t flags = 0;
#define FLAG_READ (1u << 0)
#define FLAG_WRITE (1u << 1)
#define FLAG_EXEC (1u << 2)
flags |= FLAG_READ | FLAG_WRITE; // set
printf("flags = 0x%x\n", flags);
flags &= ~FLAG_WRITE; // clear
printf("flags = 0x%x\n", flags);
int can_read = (flags & FLAG_READ) != 0;
printf("can_read = %d\n", can_read);
// Toggle
flags ^= FLAG_EXEC;
printf("flags = 0x%x\n", flags);
// Shift and mask nibbles
uint32_t v = 0xDEADBEEF;
printf("nibble = 0x%x\n", (v >> 8) & 0xF);
// Population count of a byte
uint8_t b = 0b10110101;
int count = __builtin_popcount(b);
printf("popcount = %d\n", count);
return 0;
}Explanation
Bitwise operators set, clear, toggle, and test individual bits within an integer, which is how flags and hardware registers are packed. The pattern flags & ~MASK clears bits while flags | MASK sets them. Shifting right then masking extracts a field of width n at any offset.
More C Snippets
Pointer Basics
Declare pointers, dereference, and walk an array with pointer arithmetic.
Memory Management
Allocate, resize, and free heap memory with malloc, realloc, and free.
String Operations
Use string.h helpers for length, copy, concat, compare, and tokenize.
File I/O
Open, read, write, and close files using the stdio FILE API.
Structs
Group related fields with typedef and pass by pointer for mutation.
Function Pointers
Store function addresses for callbacks and dispatch tables.