Skip to content

Instantly share code, notes, and snippets.

@pathawks
Last active September 30, 2015 03:47
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 pathawks/d94010d8f1c41581227f to your computer and use it in GitHub Desktop.
Save pathawks/d94010d8f1c41581227f to your computer and use it in GitHub Desktop.
IEEE 754 Explore
/**
* Shows how a number is represented as IEEE 754
*
* @author Pat Hawks
* Course: COMP B13
* Created: Sept 29, 2015
* Source File: ieeefloat.c
*/
#include <stdio.h>
#include <limits.h>
#include <float.h>
union Float {
float value;
int ieee;
};
long calculateMantissa(int m) {
long c = 0;
int i = FLT_MANT_DIG;
long pos = 5000000000000000;
while (--i) {
if (m & (1<<(FLT_MANT_DIG-1))) {
c += pos;
}
m <<= 1;
pos >>= 1;
}
if (c) {
while (c % 10 == 0) {
c /= 10;
}
}
return c;
}
int main(void) {
union Float num;
int sign;
int mantissa;
int exponent;
char const* const prompt = "Please enter a floating point decimal number: ";
char const* const table = "\n Sign Exponent Mantissa\n Value: %3d 2^%-6d 1.%ld\nEncoded as: %3d %-8d %d\n";
printf("%s", prompt);
scanf("%f", &num.value);
sign = (num.ieee & INT_MIN)?0:1;
mantissa = num.ieee & ((1 << (FLT_MANT_DIG-1)) - 1);
exponent = ((num.ieee) >> (FLT_MANT_DIG - 1)) & UCHAR_MAX;
printf(table, sign==0?1:-1, exponent-127, calculateMantissa(mantissa), sign, exponent, mantissa);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment