Search code examples
c++bit-manipulationbitwise-or

Determining original Constants from bitwise OR combinations


Say I have only two flags (bCold and bHot) that are getting set. I've discovered what all possible combinations should equal. How then can I determine what the original (or compatible) constants would be from the below?

When bCold and bHot are both turned ON = 0x4100
When bCold and bHot are both turned OFF = 0x8200

If bCold is ON and bHOT is OFF =  0x8100
If bCold is OFF and bHOT is ON =  0x4200

Knowing the above, what should I set bCold and bHot to equal?

#define bCold  ((ULONG)0x???)
#define bHot   ((ULONG)0x???)

// Turn them on sometime later
long lCONFIG_FLAGS = bCold | bHOT; 

Solution


  • Let's say that 0bXXXXXXXY means binary where Y is the less significant bit.


    Assuming the result is set with bitwise operations:

    Your numbers are made of two bytes. The right (less significant) byte is always 0b00000000, since all numbers end with 00. Lets look at the left (more significant) byte:

    When bCold and bHot are both turned ON = 0x4100 = 0b01000001

    When bCold and bHot are both turned OFF = 0x8200 = 0b10000010

    If bCold is ON and bHOT is OFF = 0x8100 = 0b10000001

    If bCold is OFF and bHOT is ON = 0x4200 = 0b01000010

    From this you can see that the two left-most bits set the bHot, and the two rightmost bits set the bCold (right = less significant).

    So:
    
    0b01000000 = *bHot* ON -= `0x40`
    
    0b00000001 = *bCold*  ON  = `0x01`
    
    0b10000000 = *bHot* OFF = `0x80`
    
    0b00000010 = *bCold*  OFF = `0x02`
    

    Now, add the right byte, which we said is always zero, and you get

    *bHot* ON = 0x4000, OFF = 0x8000
    *bCold*  ON = 0x0100, OFF = 0x0200
    

    The result is set by bitwise "OR"


    Assuming the result is set by simply adding numbers:

    (which is wrong, because your post name include the bitwise OR mention, but still let's try it just for fun) A simple equation will show us these figures:

    *bCold* OFF: 0x0200, ON:  0x0100
    *bHot*  OFF: 0x8000, ON:  0x4000
    

    The result could be set by simply adding the numbers, e.g. 0x0200 + 0x8000 = 0x8200 for both OFF.


    Conclusion

    As you can see, so the final result is:

    *bCold* OFF: 0x0200, ON: 0x0100
    
    *bHot*  OFF: 0x8000, ON: 0x4000