Simple example on how to compare for greater/smaller floating points and signed integers with one single procedure.
See: http://kkoral.blogspot.com/2014/09/agnostic-type-int-float-greatersmaller.html
Simple example on how to compare for greater/smaller floating points and signed integers with one single procedure.
See: http://kkoral.blogspot.com/2014/09/agnostic-type-int-float-greatersmaller.html
/* 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; | |
} |