Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print binary representation of a float number in C++ [duplicate]

Possible Duplicate:
Float to binary in C++

I want to print out the binary representation of a float number in C++. Not very practical, just out of curiosity.

The following program doesn't compile though. The reinterpret_cast fails. What kind of cast can I use so that I can do the " &(1 << i) " part?

#include <iostream>
using namespace std;


void toBinary(float num) {
  int numi = reinterpret_cast<int>(num);
  cout << num << " " << numi << endl;
  for (int i = 0; i < 8 * sizeof(num); i++){
    if (numi & (1<<i)) {
      cout << 1;
    } else {
      cout << 0;
    }
  }
  cout << endl << endl;
}

int main() {
  float a;
  cout << sizeof(int) << " " << sizeof(float) << endl;
  a = 13.5;
  toBinary(a);
  toBinary(13.9);
  toBinary(2 * a);
  toBinary(-a);
}
like image 629
Petko M Avatar asked Dec 04 '22 10:12

Petko M


1 Answers

There's a much easier way. Take a pointer to the float, and reinterpret_cast it to a pointer to char. Now loop through sizeof(float) and convert each char to 8 binary digits. This method works for doubles too.

like image 115
Mark Ransom Avatar answered Dec 26 '22 14:12

Mark Ransom