Skip to content

Instantly share code, notes, and snippets.

@jrelo
Created August 7, 2024 14:05
Show Gist options
  • Save jrelo/83b0e2c1ce0e2769140d08a76d12c779 to your computer and use it in GitHub Desktop.
Save jrelo/83b0e2c1ce0e2769140d08a76d12c779 to your computer and use it in GitHub Desktop.
bitmask logic
#include <stdio.h>
/*
Common bitmask operators and logic:
1. AND (&)
Purpose: Clear (set to 0) specific bits or only show bits that are already set.
Example: result = value & mask;
Keeps bits that are 1 in both value and mask.
2. OR (|)
Purpose: Set specific bits to 1.
Example: result = value | mask;
Sets bits to 1 where the mask has bits set to 1.
3. XOR (^)
Purpose: Toggle specific bits.
Example: result = value ^ mask;
Toggles bits where the mask has bits set to 1.
4. NOT (~)
Purpose: Invert all bits.
Example: result = ~value;
Flips all bits in value.
*/
int main() {
unsigned char value = 0b10101111; // Example value
unsigned char mask = 0b00001100; // Example mask
// Clearing specific bits
unsigned char clear_bits = value & ~mask;
// Setting specific bits
unsigned char set_bits = value | mask;
// Toggling specific bits
unsigned char toggle_bits = value ^ mask;
// Showing only set bits
unsigned char show_set_bits = value & mask;
printf("Original value: 0b%08b\n", value);
printf("Mask: 0b%08b\n", mask);
printf("Cleared bits: 0b%08b\n", clear_bits);
printf("Set bits: 0b%08b\n", set_bits);
printf("Toggled bits: 0b%08b\n", toggle_bits);
printf("Show only set bits: 0b%08b\n", show_set_bits);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment