Non-decimal radices/Convert: Difference between revisions

→‎{{header|C}}: added the code for num to "any" base
No edit summary
(→‎{{header|C}}: added the code for num to "any" base)
Line 157:
 
=={{header|C}}==
<lang c>#include <stdlib.h> // for strtol
#include <string.h>
 
#define MAX_OUTSTR_LEN 256
char *to_base(long num, int base)
{
static char *map = "0123456789abcdefghijklmnopqrstuvwxyz";
/* TODO: implement conversion from integer to string of base */
char *result = NULL;
int i=0, j;
char t;
 
if ( base > strlen(map) ) return NULL;
 
result = malloc(sizeof(char)*MAX_OUTSTR_LEN);
*result = 0;
do {
result[i++] = map[ num%base ];
num /= base;
} while(num != 0);
result[i] = 0;
for(j=0; j < i/2; j++) { /* invert the rests */
t = result[j];
result[j] = result[i-j-1];
result[i-j-1] = t;
}
return result;
}