#include <stdio.h>
// Set bit at position pos to 1
unsigned int setBit(unsigned int num, int pos) {
return num | (1U << pos); // OR sets bit at pos
}
// Clear bit at position pos to 0
unsigned int clearBit(unsigned int num, int pos) {
return num & ~(1U << pos); // AND with NOT clears bit at pos
}
// Toggle bit at position pos
unsigned int toggleBit(unsigned int num, int pos) {
return num ^ (1U << pos); // XOR flips bit at pos
}
int main() {
unsigned int number = 45; // 00101101
int position = 3;
unsigned int set_result = setBit(number, position);
unsigned int clear_result = clearBit(number, position);
unsigned int toggle_result = toggleBit(clear_result, position);
printf("Set bit %d: %u (binary 00101101)\n", position, set_result);
printf("Clear bit %d: %u (binary 00100101)\n", position, clear_result);
printf("Toggle bit %d: %u (binary 00101101)\n", position, toggle_result);
return 0;
}return num | (1U << pos);
Set bit at position pos by OR with mask
return num & ~(1U << pos);
Clear bit at position pos by AND with inverted mask
return num ^ (1U << pos);
Toggle bit at position pos by XOR with mask
Set bit 3: 45 (binary 00101101)
Clear bit 3: 37 (binary 00100101)
Toggle bit 3: 45 (binary 00101101)