Skip to content

Instantly share code, notes, and snippets.

@suarezvictor
Created December 24, 2023 00:39
Show Gist options
  • Save suarezvictor/3ac9a31bccca094acd2438b19e11ef46 to your computer and use it in GitHub Desktop.
Save suarezvictor/3ac9a31bccca094acd2438b19e11ef46 to your computer and use it in GitHub Desktop.
Comparison operator using adders and logic
//comparison operator using adders
//(C) 2023 Victor Suarez Rovere
#include <stdio.h>
//select type (all were tested)
typedef unsigned char type;
//typedef signed char type;
//typedef unsigned short type;
//typedef signed short type;
int has_carry(size_t a)
{
return a & (1<<(sizeof(type)*8));
}
int comp1(type a, type b)
{
return a > b;
}
int comp2(type a, type b)
{
return !has_carry(a + ~b);
}
int main()
{
size_t count = 0;
type a = 0, b = 0;
for(;;)
{
for(;;)
{
int r1 = comp1(a, b);
int r2 = comp2(a, b);
if(r1 != r2)
{
printf("TEST NOT PASSED: a=%d, b=%d, first result=%d, second result=%d\n", a, b, r1, r2);
return 1;
}
++count;
if(++b == 0)
break;
}
if(++a == 0)
break;
}
printf("TESTS PASSED, count=%ld\n", count);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment