forty_tw0
forty_tw0

Reputation: 35

How to implement logical operators using bitwise operators

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.

Upvotes: 1

Views: 549

Answers (1)

Bathsheba
Bathsheba

Reputation: 234635

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.

Upvotes: 5

Related Questions