Skip to content

Instantly share code, notes, and snippets.

@AndreaCorallo
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreaCorallo/6b1dbfe946297179d3c4 to your computer and use it in GitHub Desktop.
Save AndreaCorallo/6b1dbfe946297179d3c4 to your computer and use it in GitHub Desktop.
Agnostic type int float greater/smaller number comparison
/* Function for encoding the floating point numbers */
/* (because decoding is symmetric this func will serve also this purpose) */
int32_t encode_float(float f) {
int32_t *p;
p = (int32_t *) &f;
if (f < 0)
*p = 0x80000000 | ~*p;
return *p;
}
/* Complete test program using a macro instead of the encoding function. */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdint.h>
#include <unistd.h>
#define NTEST (1 << 20)
#define TRANS_FLOAT(f) (f < 0 ? 0x80000000 | ~*(int32_t*)&f : *(int32_t*)&f)
int main (int argc, char *argv[])
{
int i;
int32_t int1, int2;
float float1, float2;
int rnd = open("/dev/urandom", O_RDONLY);
for (i = 0; i < NTEST; i++) {
do
read(rnd, &float1, sizeof(float));
while (!(float1 == float1));
do
read(rnd, &float2, sizeof(float));
while (!(float2 == float2));
int1 = TRANS_FLOAT(float1);
int2 = TRANS_FLOAT(float2);
if ((int1 > int2) != (float1 > float2)) {
printf("FAILURE iteration %d\n", i);
printf("float couple:\t%E\n\t\t%E\n", float1, float2);
printf("int couple:\t%d\n\t\t%d\n", int1, int2);
exit(1);
}
}
close(rnd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment