Pages

Saturday, January 9, 2016

Print a float or double in C++?

#include <iostream>
#include <bitset>
#include <cassert>

using namespace std;

int main(void)
{
const int n = sizeof(float)* 8; //32 bits
float f = 975.75;
unsigned int u;
assert(sizeof(f) == sizeof(u));
std::memcpy(&u, &f, sizeof(f));
std::cout << n << ": " << bitset<n>(u) << endl;
//32: 01000100011100111111000000000000

const int nd = sizeof(double)* 8;
double d = 975.75;
unsigned long long ull;
assert(sizeof(d) == sizeof(ull));
std::memcpy(&ull, &d, sizeof(d));
std::cout << nd << ": " << bitset<nd>(ull) << endl;
//64: 0100000010001110011111100000000000000000000000000000000000000000

std::system("pause");
return 0;
}

To confirm the conversion, please check out: http://www.binaryconvert.com/index.html

No comments:

Post a Comment