#include <stdio.h>
void replace_bit(int *first, int second, int pos) {
int bit_at_specified_pos = (second >> pos) & 1;
if (bit_at_specified_pos == 1) {
bit_at_specified_pos = bit_at_specified_pos << pos;
*first |= bit_at_specified_pos;
}
else {
int all_bits_1 = 255;
bit_at_specified_pos = 1 << pos;
// set the specified position bit to 0
all_bits_1 = all_bits_1 ^ bit_at_specified_pos;
*first &= all_bits_1;
}
}
int main()
{
int first = 7; // 0111
int second = 8; // 1000
int pos = 3;
replace_bit(&first, second, pos);
printf("%d\n", first); // 1111
first = 7; // 0111
second = 11; // 1011
pos = 2;
replace_bit(&first, second, pos);
printf("%d\n", first); // 0011
return 0;
}
/*
run:
15
3
*/