This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Testing variable bit

I'm having some problems testing bit 0 of a variable to see if it's a 1. Here's the snippet of the code:

if ((bWork && 0x01)==1)
       bTemp = bTemp|0x01;
else
       bTemp = bTemp & 0xFE;

The problem is that whenever bWork > 0 (such as when bWork = 0xFC), it drops into the if statement even though it should be zero and drop into the else statement.
I probably have a syntax error but don't see it.

Parents
  • You are using a logical AND instead of a bitwise AND. The following code does what you want:

    if ((bWork & 0x01)==1)
           bTemp = bTemp|0x01;
    else
           bTemp = bTemp & 0xFE;
    

    Note that this if...then stuff could all be handled with bitwise logic using the following statement:

    bTemp ^= (bWork & 0x01);

    This generates about half the code of the if...then.

    Jon

Reply
  • You are using a logical AND instead of a bitwise AND. The following code does what you want:

    if ((bWork & 0x01)==1)
           bTemp = bTemp|0x01;
    else
           bTemp = bTemp & 0xFE;
    

    Note that this if...then stuff could all be handled with bitwise logic using the following statement:

    bTemp ^= (bWork & 0x01);

    This generates about half the code of the if...then.

    Jon

Children
No data