I’m having trouble with an algorithm.
I have a byte used for IO of which certain bits can be set with a method called XorAndXor.
The algorithm works as follows:
newValue = (((currentValue XOR xorMask1) AND andMask) XOR xorMask2)
The description reads:
If both xor-masks have the same value then this function inserts the
bits of the xor-mask into the bit locations where the and-mask is
1. The other bits remain unchanged.
So what I expect from this function is when I have the following byte: 00101101 and I use 01000000 for both xor-masks and as the and-mask, that only the second bit would be set to 1 and the result would be 01101101.
However, when doing the math and going through the functions, the result is 00000000.
What am I doing wrong or is there something about this function that I don’t understand? This kind of low level programming has been a while so I don’t really know if this is a methodology used often and why and how you should use it.
Let me just ask this simple question: Is there a way to use this function effectively to set (or unset/change) a single bit (without asking specifically for the current value)?
For example: The current value is 00101101 (I don’t know this), but I just want to make sure the second bit is set, so the result must be 01101101.
Important Info In my documentation PDF, it seems there is a little space between XOR and the first xorMask1, so this may be where a ~ or ! or some other negation sign might have been and it could very well be lost due to some weird encoding issues. So I will test the function if it does what the documentation says or what the function declaration says. Hold on to your helmets, will post back with the results (drums please)….
I’ve been studying this for a while now, and I think I see what others are not. The XOR AND XOR process is useful for setting multiple bytes without disturbing others. and Example, we have a given byte where we want to set to 1x1x xxx0 where the x’s are values we don’t care about. Using the XOR AND XOR process, we use the following masks to turn the bits we don’t care about on and off. We use the XOR mask to turn bits on and the AND mask to turn bits off, the ones we don’t care about for the mask we leave at a default value (0 for an XOR mask [x XOR 0 = x] and 1 for a AND mask [x AND 1 = x]). So given our desired value, our masks look like this:
If our mystery bit reads 10010101, the math then follows:
The bits we want on are on, and the bits we want off are off, regardless of their prior state.
This is a nifty bit of logic for managing multiple bits.
EDIT: the last XOR is for toggling. If there is a bit that you know needs to change, but not what to, make it a 1. so lets say we want to toggle the third bit, or masks will be:
The last interaction would then change to
and the third bit is toggled.