Logic Problem

18 Feb 2010

Hi all,

Hoping someone can help me here. I have a program with a byte made up of 8 status flags. I want to run a piece of code only if bit 7 is high AND bits 6, 2 & 1 are all low. So far I have ...

 if((Status&0x80)&&(~(Status|0x46))){ Run code here}

This doesn't work how I thought it would, can someone put me out of my misery?

Thanks

Martin

 

18 Feb 2010

Try:

if((Status&0x80)&&(~(Status&0x46))){ Run code here}

(Change the | to an & to extract just the bits you want to be low, before inverting)

 

Dan

18 Feb 2010

Hi Martin, Dan,

Remember ~ means "invert", and not "not", hence ~(Status & 0x46) will always be true (as there will always be some bits 0 before inversion).

Changing ~ to ! should make this work. i.e it is only true if all bits are 0.

However, another approachof constructiong your logic may be more readable. If you think about it, you are checking some bits for a fixed value, and ignoring others. Therefore, a natural construct might mask the ignored bits to 0, then compare to the desired result with 0's in don't care positions:

if((VALUE & MASK) == DESIRED)

so in your case:

if((Status & 0xC6) == 0x80)

Appologies in advance if I slipped up, but you get the idea.

Simon

19 Feb 2010
Simon Ford wrote:

so in your case:

if((Status & 0xC6) == 0x80)

Hi Simon, Dan,

Thanks for your help, I've just worked through the logic and I'm pretty sure this will now work.  I'll try it tonight.

Martin