First I select the mode, do I need to set bit or clear bit.
Setting bit is easy-er. I start with the (1 << pos) part. This part of the code means that I take number 1 and shift it to the left the same amount of times as the variable pos. If i convert the number 1 into binery it would look like this 00000001. I can imagine that the pos = 3, (00000001 << 3)so the number 1 will be shifted 3 times to the left giving us the result of 00001000. Perfect...now the juicy part!
The number in reg for example 10 in binary is 00001010
reg |= (1 << pos) == 10|= (1 << 3) == 00001010|= ( 00000001 << 3)
This command |= will do the last lift. It will do the math and store the value in its self. So it could be written as well like this " reg = reg | (1 << pos) ". Then its only the matter of fact .....what dose the | thingy dose? Well, it is a OR operand, in short:
0001 <- first number 0000 0001 0000
0001 <- second number 0001 0000 0000
==== ===== ==== ====
0001 <-result 0001 0001 0000
If one of the numbers are 1 then the result will be 1.
In our case:
00001010
00001000
========
00001010
Result didnt cahnge becouse there was already 1.
Something similar is happening in mode 0, but it has the opposite meaning. If it finds a matching 1, it will write 0 in its place.
00001010
00001000
========
00000010
Hope it helped out someone :D
#include <stdio.h>
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
if(mode == 1){
reg |= (1 << pos);
return reg;
}else if(mode == 0){
reg &= ~(1 << pos);
return reg;
}
}
int main() {
unsigned char reg;
int pos, mode;
scanf("%hhu %d %d", ®, &pos, &mode);
printf("%d", modifyBit(reg, pos, mode));
return 0;
}
Input
10 3 1
Expected Output
10