Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <iostream>
#include <string.h>
#include <cmath>
int getInt(const char sym)
{
switch(sym)
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'a': case 'A': return 10;
case 'b': case 'B': return 11;
case 'c': case 'C': return 12;
case 'd': case 'D': return 13;
case 'e': case 'E': return 14;
case 'f': case 'F': return 15;
default: return -1;
}
}
char getChar(const int num)
{
switch(num)
{
case 0: return '0';
case 1: return '1';
case 2: return '2';
case 3: return '3';
case 4: return '4';
case 5: return '5';
case 6: return '6';
case 7: return '7';
case 8: return '8';
case 9: return '9';
case 10: return 'a';
case 11: return 'b';
case 12: return 'c';
case 13: return 'd';
case 14: return 'e';
case 15: return 'f';
default: return NULL;
}
}
int getDecimal(const char *from, const int base)
{
int temp, num = 0;
bool isHex = (base > 10 && base <= 16);
for(size_t i = 0, len = strlen(from); i < len; i++)
{
temp = getInt(from[i]);
if(temp == -1 || (!isHex && temp > 9)){
return -1;
}
num += temp * pow((double) base, len - i - 1);
}
return num;
}
const char *convert(int num, int base)
{
int prev, temp = num, size = 0;
while(temp != 0)
{
size++;
temp /= base;
}
char *res = new char [size];
for(int i = size - 1; i >= 0; i--)
{
prev = num;
num /= base;
res[i] = getChar(prev - num*base);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment