Created
October 6, 2014 18:10
-
-
Save pashazz/c3fe961bceb378806b31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace std; | |
void decToBinary_helper(string &str, int dec); | |
std::string decimalToBinary(const std::string &src) | |
{ | |
/* | |
decimalToBinary: returns binary representation of number in src, or Error. | |
*/ | |
istringstream myistream(src); | |
int decRepr = 0; | |
if(!(myistream >> decRepr)) | |
return string("Error!"); | |
string str = ""; | |
decToBinary_helper(str, decRepr); | |
return str; | |
} | |
void decToBinary_helper(string &str, int dec) | |
{ | |
/* | |
decToBinary_heloper | |
input: ostringstream to write numbers in; current decimal representation 'dec' | |
output: os will contain reversed number in bin format | |
*/ | |
if (dec == 1) | |
str.insert(str.begin(), '1'); | |
else | |
{ | |
if (dec % 2 == 0) | |
str.insert(str.begin(), '0'); | |
else | |
str.insert(str.begin(), '1'); | |
decToBinary_helper(str,dec/2); | |
} | |
} | |
void numbersToBinary(string &src) | |
{ | |
for (int i = 0; i < src.length(); ++i) | |
{ | |
if (isdigit(src[i])) | |
{ | |
int numberStart = i++; //numberStart = iter; | |
while (src.length() != i && (isdigit(src[i]))) | |
{ | |
++i; | |
} | |
string ins = decimalToBinary(src.substr(numberStart, i-numberStart)); | |
src.replace(numberStart, i-numberStart, ins); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment