[英]How can I efficiently perform == using binary operations?
I am interested in finding a Boolean/arithmetic function that will return -1 if two values match, and 0 if they do not match, in other words the == operation. 我对寻找一个布尔/算术函数感兴趣,如果两个值匹配,该函数将返回-1,如果两个值不匹配,则返回0,即==操作。 I know this can be done with a logical NOT, for example:
我知道这可以通过逻辑非完成,例如:
! ! (AB)
(AB)
which will be -1 (= 111111111.... in binary) if A == B. But the problem is that this compiles to a big right shift, like >> 31
which is expensive. 如果A == B,则将为-1(以二进制表示= 111111111 ....)。但是问题是,这会编译为较大的右移,例如
>> 31
,这很昂贵。 I was hoping to find short cycle binary instructions that could achieve the same effect. 我希望找到可以达到相同效果的短周期二进制指令。
How does == compile when used as an R-value, same way as !(AB)? 与R!(AB)相同时,==如何用作R值进行编译?
would this help? 这会有所帮助吗?
#include <stdio.h>
int compare (int a, int b) {
char res[] = { 0, 0, -1};
char *p = &res[2];
return p[(a - b) ^ (b -a)];
}
main() {
printf("\nans %d \n", compare(12435, 12435));
printf("\nans %d \n", compare(221, 12435));
printf("\nans %d \n", compare(-43221, 12435));
}
BTW You can use a ^ b to get 0 for equal BTW您可以使用a ^ b等于0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.