Copyright © Programs ++
Design by Dzignine
Sunday 1 April 2012

Decimal to Binary conversion program (v2.0)

The program I posted in my previous post could only convert whole decimal numbers into binary. Meaning it could not convert decimal numbers like 2.34 into its binary equivalent. This is the updated version of that program, and this one is capable of converting any decimal number into its binary equivalent.

Pleas read the post : Decimal to binary conversion , if you are new to this concept.

// Program to convert decimal to binary ( version 2.0 )

#include <iostream>

void convert_integer(int arr[],int x) // function to convert the integer part to binary
{
     int i=0;
     while ( x != 0 ) // until x is fully divided, leaving only 1
     {
          arr[i] = x%2; // store the remainder in the array
          x = x/2;
          i++;
     }
     /*since arrays are passed by refernce, hence any changes in the parameter array will
        result in change in the array passed as the argument */

} // end of function

void convert_float(int arr[],double x) // function to convert the floating part into binary
{
     int i=0;
     do
     {
          x = x * 2;
          if ( x > 1 )
          {
               arr[i] = (int)x;
               x = x - (int)x;
          }
          else
          arr[i] = (int)x;
          i++;
     }while ( x != 1 && i != 8);

}// end of function

int main()
{
     double value;
     int arr1[8] = {0,0,0,0,0,0,0,0}; // for integral part
     int arr2[8] = {0,0,0,0,0,0,0,0}; // for floating part
     std::cout<<" Enter a number to convert : ";
     std::cin>>value;
     convert_integer(arr1,(int)value);
     double temp = value - (int)value;
     convert_float(arr2,temp);

     std::cout<<" \n The binary output (8-bit ) is : ";

     for (int i=7; i>=0; i--) // displays the LHS of the binary number
          std::cout<<arr1[i]<<" ";

     std::cout<<" . "; // adds the decimal(point) between the numbers

     for (int i=0; i<8; i++) // displays the RHS of the binary number
          std::cout<<arr2[i]<<" ";

     return 0;
} // end of main

------ OUTPUT ------

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.

------ Related Posts ------

1 comments:

  1. Thanks for this very helpful blog! :) This will be very helpful for me and my groupmates. ♥

    ReplyDelete

Comment Here....