code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
Terms of Agreement:
By using this code, you agree to the following terms...
1) You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for langauges that allow it) freely and with no charge.
2) You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
3) You may link to this code from another website, but ONLY if it is not wrapped in a frame.
4) You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
/********************************************************
* Program: Binary to decimal and vice versa converter *
* Author: Musawir Ali *
* Version: 1.0 *
********************************************************/
#include
#include
#include
using namespace std;
void main()
{
string binary; //string to hold the binary string
int bit; //translate a character bit to an int value
int decimal=0; //int to hold the decimal value
char read; //char to read through the binary string
/******** Input binary string *********/
cout << "Input a binary string: ";
cin >> binary;
/********************
* Go through the string, read a char, multiply with appropriate power of 2
* and keep increasing the decimal value.
**********************/
for(int i=0; i { read = binary[i]; if(read == '0') bit = 0; else bit = 1; decimal = decimal + ((pow(2,(binary.size() - i -1)))*bit); } cout << "The number is " << decimal << endl; /******** Input decimal number *********/ cout << "\nEnter decimal number: "; cin >> decimal; binary=""; //initialize binary string int max=0; //the max power of 2 i=0; //initiazlie i to 0; int string_size=0; //keeping track of binary string value /****** Find the max power of 2 **********/ while(max < decimal) { i++; max = pow(2,i); } /************ * if the max power of 2 is exactly the value of decimal, * then add a '1' to the binary string and i 0's. ************/ if(max == decimal) { binary = binary + '1'; for(int j=0;j
binary=binary+'0'; } /************ * else add a '1' to the begining of the string, * check if the next '1' would be still less than or equal * to the decimal value. Keep doing that for i times. ************/ else { i=i-1; binary=binary+'1'; string_size = string_size + (pow(2,i)); for(int j=i;j>0;j--) { i--; if((string_size + pow(2,i)) <= decimal) { string_size = string_size + pow(2,i); binary = binary + '1'; } else binary = binary + '0'; } } cout << "The binary string is: " << binary << endl; cout << "\nEnd of demonstration!" << endl; } Other 16 submission(s) by this author