Skip to content

Instantly share code, notes, and snippets.

@k4rtik
Created December 9, 2011 23:23
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 k4rtik/1453795 to your computer and use it in GitHub Desktop.
Save k4rtik/1453795 to your computer and use it in GitHub Desktop.
Program to check whether the compiler converts a given floating point number to the IEEE 754 specification. - February 25, 2011
/*
* ieee754.c
*
* Program to check whether the compiler converts a given floating point number
* to the IEEE 754 specification.
*
* Original Authors: Mohammed Hashir and Ashwin Jacob
* This is a slightly modified and improved version by
*
* Kartik Singhal - B090566CS
*
* Special thanks to the original authors.
*/
#include <stdio.h>
#include <math.h>
void strev(int *s, int l)
{
int tmp;
int f = 0;
while (f < l) {
tmp = s[f];
s[f] = s[l];
s[l] = tmp;
f++;
l--;
}
}
int main()
{
float fnum, *z;
int a[33], c[24], b[8];
int i, k, m, q=0, s;
for(k = 30; k >= 20; k--)
q = q | (1<<k);
z = (float*)&q;
float p;
p = 0.0;
m = 0;
printf("Enter a floating point number: ");
scanf("%f", &fnum);
int *ptr=(int*)&fnum;
i = *ptr;
for(k = 0; k < 32; k++)
{
if(i & (1<<k))
a[k] = 1;
else
a[k] = 0;
}
strev(a, 31);
s = a[0];
for(k = 0; k<8; k++)
b[k] = a[k+1];
for(k = 0; k<23; k++)
c[k] = a[k+9];
printf("\nSign Bit (31): %d", s);
printf("\nExponent Field (30 - 23): ");
for(k = 0; k<8; k++)
printf("%d", b[k]);
printf("\nSignificand (22 - 0): ");
for(k = 0; k<23; k++)
printf("%d", c[k]);
strev(b, 7);
strev(c, 22);
for(k = 0; k<8; k++)
{
if(b[k] == 1)
m = m+pow(2, k);
}
for(k = 0; k<23; k++)
{
if(c[k] == 1)
p = p+pow(2, k-22);
}
printf("\n\nDecimal value of exponent field: %d", m);
printf("\n");
if(m == 0 && p == 0.0)
printf("\nZero\n");
else if(m == 0 && p != 0.0)
printf("\nDenormalised number\n");
else if(m > 0 && m < 255)
printf("\nNormalised number\n");
else if(m == 255 && p == 0.0 && q <= (3.40282367 * pow(10, 38)))
printf("\nInfinity\n");
else if(m == 255 && q != 0.0)
printf("\nNaN\n");
return 0;
}
/*
Sample Output
=============
Output verified from the IEEE-754 floating point converter at http://babbage.cs.qc.edu/IEEE-754/Decimal.html
kartik@PlatiniumLight:/media/Voyager$ gcc ieee754.c -lm
kartik@PlatiniumLight:/media/Voyager$ ./a.out
Enter a floating point number: 42
Sign Bit (31): 0
Exponent Field (30 - 23): 10000100
Significand (22 - 0): 01010000000000000000000
Decimal value of exponent field: 132
Normalised number
kartik@PlatiniumLight:/media/Voyager$ ./a.out
Enter a floating point number: -42.25
Sign Bit (31): 1
Exponent Field (30 - 23): 10000100
Significand (22 - 0): 01010010000000000000000
Decimal value of exponent field: 132
Normalised number
kartik@PlatiniumLight:/media/Voyager$
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment