1
votes

I have the code to convert a number to binary but can't figure out how to make it work for a fixed point decimal number. For example, how could I convert a number such as 5.25?

Here is the code I have right now:

#include <iostream>
#include <vector>
using namespace std;
int main()
{   
   vector<int>  intVector;  
   int number, digit ;
   int base ;

   cout << "Enter a base: ";
   cin >> base;

   cout << "Enter a number: ";
   cin >> number; 

   while(number > 0)
   {
      digit = number % base ;
      intVector.push_back(digit) ;
      number = number / base ;
   }
   while(!intVector.empty())                
   {
      cout<<intVector.back() ;             
      intVector.pop_back();                     
   }

   return 0;
}

Any pointers how to convert a fixed decimal number? I need it to print up to 20 decimal places.

1
umm atof or any of its companions cplusplus.com/reference/cstdlib/atofpm100
The variable 'base' is user input, so it's not necessarily going to be 2, right? You say "convert to binary" but it looks like this program can convert an integer to base 5 or base 12 or base 17, depending on how the user responds to "Enter a base".David K

1 Answers

0
votes

You could reinterpret_cast your floating point number address to a char*, and manually go over the bits one by one, something like :

double number = 16.4566565776765;

char* fp = reinterpret_cast<char*>(&number);

for (std::size_t i = 0; i < sizeof(float); i++){
    for (std::size_t j = 0; j < CHAR_BIT; j++){
        intVector.push_back(fp[i] & (1<<j) ? 1 : 0);
    }
}

Note:

  • You would need to take care of the endianess of the platform for the ordering of the bits.