Well, we are ready to set/unset register bits. If you need to refresh your memory, you can read Meeting the Bits, Let's Shift and Bitwise Operations.
We already set a bit flag here, let's reproduce that.
Set.
Generally speaking, to set the ith bit in a byte (or, an 8bit register) we do as follows:
And that's it. The above is used to set a bit (a.k.a. put a bit state to 1) keeping the rest bits as they were in the byte (from now on and within this article scope register and byte will have the same meaning when there's no need to clarify that the register 8bits long). Setting the ith bit could be thought as enabling a feature if the register has a feature on the ith bit that is considered enabled when that bit value is 1. If you remove the '|' and use only the equal sign, then you are overwritting all bit values that the register had before and asigning the new byte. This is trivial, as you are asigning and not adding (remember, '|' could be thinked of as it where an addition).
Unset.
If now what you want to do is to unset a bit but keeping the rest of them as they were, then all you need to do is this:
Let's go through it.
1. We shift the 1 to the desired position as we talk before. What we have is a byte with only a bit set in the ith position. All the other bit values are zero. 2. We negate the whole expression. Then, all the 0s became 1s, and the only bit that is 1 became 0. With this we achieve the use of the neutral element for the AND operation as we saw here. If with this new byte we do the AND operation, we are absorbing only 1 bit. That is, the bit with the value of 0, and we are neutralizing the rest values keeping it as they were.
As simple as that. Again, if you wish only to set the ith bit, you can get rid of the '&' operator (it's obvios, but...) and you will be overwritting the value the byte had.
How useful is this? Well, using numbers to remember a feature of a register it's not the best idea. I don't have good memory, so the best thing to do it's to keep this ith values denoted by their named feature. Afortunately, almost all libraries we'll use to program our favourite micro will came with that defined.
But, suppose we are on the example of our post with f0 to f7 features. Then, we can code something like this:
think we are covered now! Happy settin/unsetting!!






