简体   繁体   English

如何使用按位运算符实现逻辑运算符

[英]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.我想如果没有人有任何解决方案,我可能会转向 HDL 并看看它合成了什么。

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可以写成!!a & !!ba || b是很有诱惑力的。 a || b as !!a | !!b a || b作为!!a | !!b !!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 true || A , A is not evaluated, and for false && B , B is not evaluated. true || A , A未评估,对于false && BB未评估。 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.因此,例如定义了a++ && a++ ,但未定义a++ & a++

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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