Page 1 of 1

Usage of Logical AND Bitwise AND

Posted: Fri Apr 20, 2012 2:29 pm
by Jay Dee
Hi all,
As soon as I start to play with logical and bitwise operators my brain fries and I would like to make sure I dont pick up bad habbits!
I would like to be able to get the logical state ( 0 or 1 ) of a specific bit within a byte, is this the best way;

Result = (Byte AND Mask)&&1

Am I correct in the following assumptions,
Bitwise AND can be implemented in a calculation component using either AND or &
Logical AND is implemented only by using &&

Also I wanted to ensure that I avoided any divide by zero situations, is there a simple technique to use?
Thanks,
John.

Re: Usage of Logical AND Bitwise AND

Posted: Fri Apr 20, 2012 2:40 pm
by JonnyW
Hello. I would not do it this way - logical operators may implement branches or logic that is unnecessary for this specific use, or may result in odd behaviour when the code is optimised.

For bitwise operations you could do any of the following to achieve the same result:

Code: Select all

Result = (Byte >> Shift) AND 1          // Where Mask = (1 << Shift)
Result = (Byte AND Mask) >> Shift       // Where Mask = (1 << Shift)
Result = !!(Byte AND Mask)
Result = ((Byte AND Mask) != 0)
I would recommend the first line if you know the specific bit you're after, or the last line if you don't.

You are correct in your assumptions. I think in v4 either of the &&, & operators can be used wherever the other is - this is certainly true in v5.

For divide by zero, it depends what you are doing and to your results as to how to avoid divide by zero. A simple technique is to do:

Code: Select all

  result = numerator / (denominator + (denominator == 0))
Which will add 1 to the denominator if it is zero, but this may not be what you want. Usually it is better for clarity's sake to perform a specific check with a decision icon. This way you can handle the div-zero error much better.

Cheers,

Jonny