I'm a beginner so some of the part of my code might seems stupid and redundant, please just ignore them for now.
I'm doing an assignment where I need to write a function to add two floating point number using the IEEE 754 standard. Here are some of the requirements:
- The two numbers are represented using unsigned int and can be assumed as non negative.
- I'm not allowed to use float, double; only AND, OR, XOR or NOT are permitted.
- I don't need to handle overflow and underflow and it is assumed that the exponent is stored in the bias-127 format.
#include <stdio.h>
#include <math.h>
typedefunsignedint bit32;
//Printing the bit32 in Hexadecimal
void printhex(bit32 x){
printf("%.8x ", x);
}
//Retrieving the sign bit
unsignedint sign(bit32 value){
return value >> 31;
}
//Retrieving the expon bits
unsignedint expon(bit32 value){
return (value >> 23 & 0xff);
}
//Retrieving the mantissa bits
unsignedint frac(bit32 value){
return (value & 0x7fffff);
}
//Returns the bit32 representation of a number given the sign, exponent and fraction values
bit32 float_32(unsignedint sign, unsignedint exp, unsignedint frac){
bit32 value = 0x00000000;
value = value & (sign << 31);
value = value | (exp << 23);
value = value | frac;
return value;
}
//The value of the addition of two bit32 values x and y as a floating point bit32 value
bit32 fp_add(bit32 x, bit32 y){
//If x == 0 and y != 0, then return y
if((x | 0x0) == 0x0 && (y | 0x0) != 0x0){
return y;
}
//If x != 0 and y == 0, then return x
elseif((y | 0x0) == 0x0 && (x | 0x0) != 0x0){
return x;
}
//If both is 0, just return either of them
else{
return x;
}
bit32 sign = 0;
bit32 exp;
bit32 combinedFrac;
bit32 xFrac = frac(x);
bit32 yFrac = frac(y);
int x_int = expon(x);
int y_int = expon(y);
//Convert the exponent to Decimal to compare and do bits shifting of the mantissa
if (x_int < y_int){
int diff = y_int - x_int;
xFrac = xFrac >> diff;
}
//Convert the exponent to Decimal to compare and do bits shifting of the mantissa
elseif (x_int > y_int){
int diff = x_int - y_int;
yFrac = yFrac >> diff;
}
//Add the mantissa
combinedFrac = (xFrac ^ yFrac);
if ((int)combinedFrac == 0){
return 0;
}
//How do I know when to re-normalized the mantissa and the exponent?
return float_32(0,0,0);
}
I'm having trouble trying to add 2 mantissa together and figuring out how to know when to re-normalized the mantissa and the exponent? I'd be thankful if anyone can give me some advice on how to tackle this problem. Thanks