1
votes

How can the logical operators || and && be implemented using only the bitwise operators &, ^, |, ~, >>, << the logical operator !, and +? I've looked around on stack overflow and google for someone's previous answer or some assembly implementations but haven't found anything yet. I figure if no one has any solution I might just turn to an HDL and see what it synthesizes.

1
Is this a practical question, or are you just curious? (Perhaps you're stranded on a desert island, and your compiler's && and || operators got broken during the shipwreck...)Steve Summit
@SteveSummit Yep, just out of curiosity.forty_tw0

1 Answers

5
votes

They can't be, although it would be tempting to suggest that a && b can be written as !!a & !!b and a || b as !!a | !!b.

This is because || and && have a property where the evaluation of the second argument does not happen if the result of the expression is known from the result of the first argument. E.g. for true || A, A is not evaluated, and for false && B, B is not evaluated. So if you attempted to replicate either || or && with bitwise operators, then you could well introduce side effects into your program.

Also || and && are sequencing points, whereas the bitwise operators are not. So a++ && a++ is defined for example, but a++ & a++ is undefined.