Reputation: 228
I've been racking my brain trying to come up with a solution, but am stuck.
I have a function, this function takes the input (either 0b0
, 0b1
, or 0b10
) and sets the bit of some variable - or at least it's supposed to.
The value it's changing has two states: either 0b100
or 0b101
. I want to set the respective bit from the input. This is easy for the true bits, but tricky for the false bits. Some pseudo code for all the scenarios:
if (var == 0b100 && input == 0b0) { do nothing } // bit already set
if (var == 0b101 && input == 0b0) { var = 0b100 } // bit is different, so we set it.
if (var == 0b100 && input == 0b1) { var = 0b101 } // bit is different, so we set it.
if (var == 0b101 && input == 0b1) { do nothing } // bit is already set
if (var == 0b100 && input == 0b10) { var = 0b110 } // bit is never set, so set it
if (var == 0b101 && input == 0b10) { var = 0b110 } // bit is never set, so set it
I don't want to cheat and make a separate statement for every possibility, I'd like a function for this. Here's what I've sort of strung together, but it obviously doesn't work:
if ( var ^ input )
{
var ^= input;
}
The issue with this code is that 3rd bit (far left one) is always true.
Is this even possible?
Here is the same question, just posed a different way (which will result in different answers).
A function takes input for one bit. I want to take the left most bit and compare that bit and only that bit to another variable. e.g. input = 0b10
compared to 0b101
's second bit, 0b00
, since 0b10
's left most bit is the second one.
On rare occasion, the unchanging bit may change :P (not from me though), so 0b001
or 0b000
may be it's value. For this reason, I cannot create a dynamic mask and compare only my bit.. The best method to solve my issue would be to answer this alternative question. Thanks a ton for your help, guys!
Upvotes: 3
Views: 438
Reputation:
Step 1: Mask out the lower two bits.
var &= 0b100;
Step 2: Assign the lower two bits through OR operation.
var |= input;
Note that you may need to change the bit mask in step 1 in actual code base on the actual data type.
Upvotes: 2