Skip to content

Instantly share code, notes, and snippets.

@pashazz
Created October 6, 2014 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pashazz/c3fe961bceb378806b31 to your computer and use it in GitHub Desktop.
Save pashazz/c3fe961bceb378806b31 to your computer and use it in GitHub Desktop.
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