简体   繁体   中英

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.

They can't be, although it would be tempting to suggest that a && b can be written as !!a & !!b and a || b a || b as !!a | !!b !!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. Eg for true || A 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM