Skip to content

Instantly share code, notes, and snippets.

@derrickturk
Created March 26, 2014 20:18
Show Gist options
  • Save derrickturk/9792291 to your computer and use it in GitHub Desktop.
Save derrickturk/9792291 to your computer and use it in GitHub Desktop.
Dump binary representation of IEEE double.
#include <memory>
#include <cstddef>
#include <algorithm>
#include <iostream>
#include <iomanip>
template<class T>
inline std::unique_ptr<unsigned char[]> to_bytes(const T& item)
{
std::unique_ptr<unsigned char[]> buf(new unsigned char[sizeof(T)]);
const unsigned char *p = reinterpret_cast<const unsigned char*>(&item);
std::copy(p, p + sizeof(T), &buf[0]);
return buf;
}
int main(int argc, char* argv[])
{
if (argc != 2) {
std::cerr << "Usage: " << (argc ? argv[0] : "to_bytes") << " <num>\n";
return 0;
}
double d = std::strtod(argv[1], nullptr);
auto b = to_bytes(d);
std::cout << std::hex << std::setfill('0');
for (std::size_t i = 0; i < sizeof(double); ++i)
std::cout << std::setw(2) << static_cast<unsigned int>(b[i]) << ' ';
std::cout << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment