Re: analysis of floating point values
None of the presented solutions take into account endianess. Usually when
you want to print the binary representation of something, you want the
most significant bit to be printed first and go down from there (in other
words, you just want the base-2 representation of the value in the same
way you would print a regular base-10 one).
Also, since it's trivial in C++ to make the function work with any type,
not just doubles, why not do that while we are at it?
//---------------------------------------------------------------
#include <iostream>
#include <climits>
template<typename Type>
void printBinaryRepresentation(Type value)
{
// Resolve if this is a big-endian or a little-endian system:
int dummy = 1;
bool littleEndian = (*reinterpret_cast<char*>(&dummy) == 1);
// The trick is to create a char pointer to the value:
const unsigned char* bytePtr =
reinterpret_cast<const unsigned char*>(&value);
// Loop over the bytes in the floating point value:
for(unsigned i = 0; i < sizeof(Type); ++i)
{
unsigned char byte;
if(littleEndian) // we have to traverse the value backwards:
byte = bytePtr[sizeof(Type) - i - 1];
else // we have to traverse it forwards:
byte = bytePtr[i];
// Print the bits in the byte:
for(int bitIndex = CHAR_BIT-1; bitIndex >= 0; --bitIndex)
std::cout << ((byte >> bitIndex) & 1);
}
std::cout << std::endl;
}
int main()
{
printBinaryRepresentation(0.5);
printBinaryRepresentation(-0.5f);
}
//---------------------------------------------------------------