Adding two floating point numbers using IEEE 754 standard

Hi everyone,

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h> 
#include <math.h>

typedef unsigned int bit32;

//Printing the bit32 in Hexadecimal
void printhex(bit32 x){
	printf("%.8x ", x);
}

//Retrieving the sign bit
unsigned int sign(bit32 value){
	return value >> 31;
}

//Retrieving the expon bits
unsigned int expon(bit32 value){
	return (value >> 23 & 0xff);
}

//Retrieving the mantissa bits
unsigned int frac(bit32 value){
	return (value & 0x7fffff);
}

//Returns the bit32 representation of a number given the sign, exponent and fraction values
bit32 float_32(unsigned int sign, unsigned int exp, unsigned int 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
	else if((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
	else if (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
Last edited on
Topic archived. No new replies allowed.