# Thread: Stumped by bitwise calc

1. ## Stumped by bitwise calc

Heres a test program:
Code:
```#include <stdio.h>

int main()
{
unsigned char reg = 128;
char val = 6;

reg |= val & 128;

printf("%02x\n", reg);
return 0;
}```
I am trying to clear the 7th bit of reg (has bits 0-7). I use 6 as an example... It doesnt matter since the 7th bit of 6 is 0 anyway. It doesn't clear, it still stays as 128 (should now be 0)

Heres what does work though... (This is important)... If the 7th bit of val is 1, then obviously reg's 7th bit needs to be 1 as well. "| val & 128" handles this fine. Can anyone assist me with this? I have made a truth table as well:

Code:
```reg    val     output
0       1        1
1       0        0
0       0        0
1       1        1```

Note, I am trying to do this all in one line if possible.

Is it possible?

2. Try

#define ALL_oTHER_1S_EXCEPT_7TH_BIT (calculate number here)

reg=(reg&ALL_oTHER_1S_EXCEPT_7TH_BIT);

3. Isn't this what AND is for?
Code:
```int main() {
unsigned char byte=128;
byte&=6;
printf("%d\n",byte);
}```
clears the last bit. I think you might as well just say byte&=0 tho

4. MK27, Maz:

& wont work because if the 7th bit of val is 1 and we & that with reg which 7ths bit is 0, the resulting value of reg would be 0. I need it to be 1.
| wont work either because if the 7th bit of val is 0 and we | that with reg which 7th bit is 1, the resulting value of reg would be 1. I need it to be 0.

5. Looking at your truth table, the output is 1 if and only if val is 1. Basically, you are trying to set reg's 7th bit to val's 7th bit, right?

I am not sure what is the best way of doing that, but one way is:
Code:
`reg = (val & (1 << 7)) ? (reg | (1 << 7)) : (reg & ~(1 << 7));`

6. Originally Posted by someprogr
MK27, Maz:

& wont work because if the 7th bit of val is 1 and we & that with reg which 7ths bit is 0, the resulting value of reg would be 0. I need it to be 1.
You set the 7th bit to 1 already by making the number 128. If you want to change the 7th bit in some way, the only choice is to 0. If you do not want to change the 7th bit, why are you asking how change the 7th bit?

Code:
`        reg |= val & 128;`
works like this:

Since the '&' oper takes precedence, val & 128 = 0x00. When you 'OR' it with 'reg' it becomes the 7th bit is one again!!!

8. Originally Posted by MK27
If you do not want to change the 7th bit, why are you asking how change the 7th bit?
As I noted in post #5, I think that someprogr is just trying to set the 7th bit of reg to the 7th but of val.

If I am correct, this statement:
"If the 7th bit of val is 1, then obviously reg's 7th bit needs to be 1 as well."
should have been:
"If the 7th bit of val is 1, then reg's 7th bit needs to be 1 as well; if the 7th bit of val is 0, then reg's 7th bit needs to be 0 as well."
(Removing the "obviously" because it obviously was not obvious.)