Created
November 4, 2015 13:15
-
-
Save hosaka/6337428030ee63361c29 to your computer and use it in GitHub Desktop.
Bitwise operation to toggle bits in memory.
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
#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