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

Decimal to Binary Conversion Program

My apologies to my readers for posting after such a long time. Had been caught up in examinations...!!

Anyways, this is a simple program to convert decimal numbers to binary numbers. In computers , binary numbers form the base of everything. Even numbers like 10,3,5 etc are converted into long string of 0s and 1s. For e.g. the decimal number 8 is converted into 1000. The bigger the number, the more 0s and 1s it has. Hence it makes sense to have a useful program to convert decimal numbers to binary numbers.

The program given below does that particular task. It takes in a decimal whole number and converts it into its binary equivalent.
The conversion method is quite simple. Just divide the number by 2 recursively and store its remainder side by side. Here is how the program works :
Step 1 : The program prompts the user to enter a decimal number;
Step 2 : The number is divided by 2 and its remainder stored in an array.
Step 3 : The number itself is divided by 2.
Step 4 : The loop is run backwards, and this gives us the required binary equivalent.

Read the following code for a better understanding. 

// Program to convert decimal to binary (8-bit)

#include <iostream>

int main()
{
     int arr[8] = {0,0,0,0,0,0,0,0}; // for a 8 bit binary
     int x;
     std::cout<<" Enter the value to compute (integer only) : ";
     std::cin>>x;
     int i=0;
     while ( x != 0 )
     {
          arr[i] = x%2;
          x = x/2;
          i++;
     }
     std::cout<<" \n Binary Output (8-bit) : ";
     for (i=7; i>=0; i--)
          std::cout<<arr[i]<<" ";

     return 0;
} // end of main

------ OUTPUT ------ 
  ------ Programming Advice and Tips ------

1 : The above program generates an 8 bit binary number. If you want a higher bit binary number, suppose 16-bit, then simply increase the size of the array fro
8 to 16 and initialize it accordingly.
2 : Be careful during display of the binary equivalent, keep in mind that the array has to be traversed in a descending index order i.e backwards, otherwise you
will not get the proper result.
3 : You can use the above program to convert decimal numbers into other types of numbers ( for e.g octal(base 8), just divide the number by 8.)
4 : Contact me at  : programsplusplus@gmail.com for related queries or leave a comment....you are bound to receive an answer.

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.
----- 

1 comments:

Comment Here....