Skip to content

Instantly share code, notes, and snippets.

@jprupp
Created May 15, 2012 12:24
Show Gist options
  • Save jprupp/2701357 to your computer and use it in GitHub Desktop.
Save jprupp/2701357 to your computer and use it in GitHub Desktop.
Double precision floating point disassembly/reassembly analyser
#include <cassert>
#include <cmath>
#include <iostream>
using namespace std;
void printbytes(double d) {
unsigned long long int* pi = (unsigned long long int*) &d;
unsigned long long int i = *pi;
short int e = (i >> 52 & 0x7ff) - 1023; // Exponent
unsigned long long int m = (i << 12 >> 12) + pow(2, 52); // Mantissa
double absv = m * pow(2, e-52); // Absolute value
double v = absv * (i >> 63 ? -1 : 1); // Set sign
assert(v == d);
cout << "Decimal: " << d << endl;
cout << "Hexadecimal: 0x" << hex << i << endl;
cout << "Mantissa: 0x" << hex << m << endl;
cout << "Exponent: " << dec << e << endl;
cout << endl;
}
int main() {
printbytes(2.0);
printbytes(1.0);
printbytes(3.1416);
printbytes(-1);
printbytes(-0.0008);
printbytes(-8.39293849532e87);
}
@jprupp
Copy link
Author

jprupp commented May 15, 2012

I thought it would be fun to do this now that I'm learning C++.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment