Skip to content

Instantly share code, notes, and snippets.

@hosaka
Created November 4, 2015 13:15
Show Gist options
  • Save hosaka/6337428030ee63361c29 to your computer and use it in GitHub Desktop.
Save hosaka/6337428030ee63361c29 to your computer and use it in GitHub Desktop.
Bitwise operation to toggle bits in memory.
#include <stdint.h>
#define LED_RED (1U << 1) // 1st bit, 0x2
#define LED_BLUE (1U << 2) // 2nd bit, 0x4
#define LED_GREEN (1U << 3) // 3rd bit, 0x8
int main() {
uint32_t reg = 0x800;
reg |= LED_RED; // set individual bits using the bitwise OR
reg |= LED_BLUE;
reg |= LED_GREEN;
// clear individual bits using bitwise AND and NOT
// combining all bits will work also:
// 0b1000 | 0b0100 | 0b0010 = 0b1110
// mask = ~0b1110 = 0b0001
// reg (0x80E) &= mask = 0x800 - all bits off
reg &= ~(LED_RED | LED_BLUE | LED_GREEN);
// in fact, the compiler will generate a better assembly code
// for the last instruction, simply using bit clear operation
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment