使用按位运算符消除IF语句 [英] Eliminating IF statement using bitwise operators
问题描述
我正在尝试消除IF语句,即如果我收到数字32,我想要一个"1",但是如果我收到其他任何数字,我想要一个"0".
I am trying to eliminate an IF statement whereby if I receive the number 32 I would like a '1', but any other number I would like a '0'.
32是0010 0000,所以我想到了将输入的数字与1101 1111进行异或.因此,如果我得到的数字32,我最终会得到11111111.
32 is 0010 0000 so I thought about XOR-ing my input number with 1101 1111. Therefore if I get the number 32 I end up with 1111 1111.
现在可以用任何方式对各个位进行与"运算(1111 1111),因为如果我的XOR结果之一为0,则表示我最终的与"运算值为0,否则为1?
Now is there any way of AND-ing the individual bits (1111 1111), because if one of my XOR results is a 0, it means my final AND-ed value is 0, otherwise its a 1?
使用GCC,而不是Intel编译器(因为我知道那里有很多内在函数)
Using GCC, not Intel compiler (because I know there are a lot of intrinsic functions there)
推荐答案
表达式
!(x ^ 32)
如果您坚持,
将为您解决问题.
will do the trick for you if you insist.
这将始终在C语言中工作,并且还将在几乎所有C ++设置中工作.从技术上讲,在C ++中,它的计算结果是一个布尔值,在几乎所有情况下,布尔值都将像0或1一样工作,但是如果您想要一个在技术上正确的C ++答案:
That will always work in C, and will also work in almost all C++ settings. Technically in C++ it evaluates to a boolean which in almost all circumstances will work like 0 or 1, but if you want a technically correct C++ answer:
(0 | !(x^32))
或:
(int)!(x ^ 32)
或采用更现代/更详细的C ++转换
or with the more modern / verbose C++ casting
static_cast<int>(x ^ 32)
这篇关于使用按位运算符消除IF语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!