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. I know this can be done with a logical NOT, for example:
! (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. 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)?
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
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.