Skip to content

Instantly share code, notes, and snippets.

@MacoChave
Created June 9, 2018 17:13
Show Gist options
  • Save MacoChave/48e2330e495becf1cc51f25a1a06a7ed to your computer and use it in GitHub Desktop.
Save MacoChave/48e2330e495becf1cc51f25a1a06a7ed to your computer and use it in GitHub Desktop.
Conversión entre bases numéricas
#include <iostream>
#include <math.h>
using namespace std;
/*
* CONVERT BINARY '11011' TO DECIMAL
* |__c__|__r__|__i__|_2^i_|_dec_|
* | 1101| 1 | 0 |__1__|__1__|
* | 110| 1 | 1 |__2__|__2__|
* | 10| 0 | 2 |__4__|__0__|
* | 1| 1 | 3 |__8__|__8__|
* | 0| 1 | 4 |_16__|_16__|
* |-----|-----|-----|-----|_27__|
*/
int b2d(int c, int r, int i)
{
if (r < 0 && r > 1) return -1;
int res = r * pow(2, i);
if (c != 0)
{
int exp = b2d(c / 10, c % 10, ++i);
return (exp >= 0) ? res + exp : exp;
}
}
int b2d(int n)
{
return b2d(n / 10, n % 10, 0);
}
int main(int argc, char const *argv[])
{
int binario = 0;
cout << "Binario a convertir: " << endl;
cin >> binario;
cout << "Binario:" << binario << endl;
int decimal = b2d(binario);
cout << "Decimal:" << decimal << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment