#include <stdio.h>
#include <stdint.h>
uint8_t toggle_bit(uint8_t reg, uint8_t pos) {
// Your code here
reg ^= (1 << pos);
return reg;
}
int main() {
uint8_t reg, pos;
scanf("%hhu %hhu", ®, &pos);
uint8_t result = toggle_bit(reg, pos);
printf("%u", result);
return 0;
}In C, bitwise operations allow direct manipulation of individual bits within a byte, word, or register. These operations are performed using the following operators:
Common bit-masking patterns:
reg |= (1 << n); // Set bit n
reg &= ~(1 << n); // Clear bit n
reg ^= (1 << n); // Toggle bit n
if (reg & (1 << n)) // Check if bit n is setThese operations are used to target and modify only specific bits, without disturbing others.
Bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
E.g.
To set bit 3 → reg |= (1 << 3)
To clear bit 6 → reg &= ~(1 << 6)
To check bit 0 → reg & (1 << 0)
To toggle but 3 → reg ^= (1 << 3)Input
6 1
Expected Output
4