Define Macro to toggle a bit of a PIN in C
Given PIN (value) and a bit to be toggled, we have to toggle it using Macro in C language.
To toggle a bit, we use XOR (^) operator.
Macro definition:
#define TOGGLE(PIN,N) (PIN ^= (1<<N))
Here,
- TOGGLE is the Macro name
- PIN is the value whose bit to be toggled
- N is the bit number
Example:
Output
val = 11 Aftre toggle bit 2 first time, val = 15 Aftre toggle bit 2 second time, val = 11Explanation:
- Initially val is 0x11, its binary value is "0001 0001".
- In this example, we are toggling bit number 2 (i.e. third bit of the val), initially bit 2 is 0, after calling TOGGLE(val, bit) first time, the bit 2 will be 1. Hence, the value of val will be "0001 0100" – thus, the output will be 0x15 in Hexadecimal.
- Now, the bit 2 is 1, after calling TOGGLE(val, bit) again, bit 2 will be 0 again, hence the value of val will be "0001 0001" – thus, the output will be 0x11 in Hexadecimal.
need an explanation for this answer? contact us directly to get an explanation for this answer