Write down an function named bitwisedFloatCompare(float number1, float number2)
ID: 3903904 • Letter: W
Question
Write down an function named bitwisedFloatCompare(float number1, float number2) that tests whether a floating point number number1 is less than, equal to or greater than another floating point number number2, by simply comparing their floating point representations bitwise from left to right, stopping as soon as the first differing bit is encountered. The fact that this can be done easily is the main motivation for biased exponent notation. The function should return 1 if number1> number2, return -1 if number2 > number1 and should return O if the two numbers are equal. Please note the solution is constrained to be implemented using bitwise comparison of the two numbersExplanation / Answer
Below is your code: -
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int bitwisedFloatCompare(float number1,float number2)
{
int b1;
int *bits = &b1;
uint32_t *x, *y;
int compare = 0;
x = (uint32_t *)(void *)&number1;
y = (uint32_t *)(void *)&number2;
for (*bits = 31; *bits>= 0; (*bits)--) {
if ((*x & (UINT32_C(1) << *bits))
&& !(*y & (UINT32_C(1) << *bits))) {
compare = 1;
break;
}
else if (!(*x & (UINT32_C(1) << *bits))
&& (*y & (UINT32_C(1) << *bits))) {
compare = -1;
break;
}
}
if (*bits == 31)
compare = -compare;
return compare;
}
int main()
{
float number1;
float number2;
int comparison;
number1=56;
number2=12;
comparison=bitwisedFloatCompare(number1,number2) ; // Compare two floating point numbers
if (comparison==1)
printf("%f is greater than %f ",number1,number2);
else if (comparison==-1)
printf("%f is greater than %f ",number2,number1);
else if (comparison==0)
printf("Number are equal ");
else
printf("Error ");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.