1

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:

! (A-B)

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 !(A-B)?

Tyler Durden
  • 11,156
  • 9
  • 64
  • 126
  • 3
    depends upon compiler and target architecture – Paul Beusterien May 16 '14 at 17:44
  • Further to the comment by @PaulBeusterien, [Is bit shifting O(1) or O(n)?](http://stackoverflow.com/questions/9083743/is-bit-shifting-o1-or-on). – Andrew Morton May 16 '14 at 17:48
  • eventually you have to do a compare for this result to be useful, the simplest is to just xor, either it is zero or not, and for C that is all you need, zero or non-zero. you could do a series of shifts and ors to turn the non-zero into all ones, but as mentioned at some point you need to do a compare for this exercise to be useful is it 0 or is it 0xFFFFFFFF... – old_timer May 16 '14 at 19:43
  • I thought `! (A-B)` resulted in 0 or 1, not -1. – chux - Reinstate Monica May 16 '14 at 19:45
  • 1
    something xor something will be 0 if something == something – Grady Player May 16 '14 at 20:31

1 Answers1

0

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

Pointer
  • 627
  • 2
  • 8
  • 19