Convert decimal fraction to binary number in C++


In this tutorial, we will be discussing a program to convert decimal fraction to a binary number.

For this we will be provided with a decimal fraction and integer ‘k’. Our task is to convert the given decimal fraction into its binary equivalent upto the given ‘k’ digits of decimal precision.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
//converting decimal to binary number
string convert_tobinary(double num, int k_prec) {
   string binary = "";
   //getting the integer part
   int Integral = num;
   //getting the fractional part
   double fractional = num - Integral;
   //converting integer to binary
   while (Integral) {
      int rem = Integral % 2;
      binary.push_back(rem +'0');
      Integral /= 2;
   }
   //reversing the string to get the
   //required binary number
   reverse(binary.begin(),binary.end());
   binary.push_back('.');
   //converting fraction to binary
   while (k_prec--) {
      fractional *= 2;
      int fract_bit = fractional;
      if (fract_bit == 1) {
         fractional -= fract_bit;
         binary.push_back(1 + '0');
      } else
      binary.push_back(0 + '0');
   }
   return binary;
}
int main() {
   double n = 4.47;
   int k = 3;
   cout << convert_tobinary(n, k) << "\n";
   n = 6.986 , k = 5;
   cout << convert_tobinary(n, k);
   return 0;
}

Output

100.011
110.11111

Updated on: 16-Jan-2020

387 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements