I wanted to write a function that would take a long long int
argument as well as a base and it would convert that number into an equivalent number in a different base, and return the result as a string (er, char
array). For example, the call,
convertBase(9, 5)
should return "14\0"
. For negative values, the returned string should simply have a negative sign, '-'
in front.
The code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include "convert.h"
#define MIN_BASE 2
#define MAX_BASE 36
#define MAX_LLI_REP 63
char toCharacter(int v)
{
v = abs(v);
return (v < 10)
? ('0' + v)
: ('a' + v - 10);
}
char * convertBase(long long int value, int base)
{
if (base < MIN_BASE || base > MAX_BASE) {
fprintf(stderr, "The base must be within [%d, %d].\n", MIN_BASE, MAX_BASE);
return NULL;
}
char c[MAX_LLI_REP];
int i, j = 0;
long long int quotient;
for (i = 0, quotient = value; quotient != 0; i++, quotient /= base)
{
c[i] = toCharacter(quotient % base);
}
int negative = value < 0;
char * result = (char *) malloc(sizeof(char) * (i + 1 + negative));
if (negative) {
result[0] = '-';
j = 1;
}
while (i) {
result[j++] = c[(i--) - 1];
}
result[j] = '\0';
return result;
}
I've ran a variety of test cases, such as both LLONG_MIN
and LLONG_MAX
from limits.h
, in various bases, as well as trying to convert a decimal number into a decimal number (expecting the same answer). It passed in all of these cases. However, I was wondering if additional sets of eyes could spot potential errors. Also, any stylistic or performance improvement suggestions would be appreciated.