base conversion in C - CodeCall Programming Forum
- I just made a function, only using integers for representation. It's able to convert from decimal to Base-(2...9) Base-11 and up is not supported, because it's requires special signs, and not only digits. Here you're...
Code:
// The function
// First parameter: The base to convert to
// Second parameter: The number to be converted
int GetBase(int iBase, int iNumber)
{
if(iBase < 2 || iBase > 10)
return 0;
int iResult = iNumber % iBase;
int iMultiplier = 10;
while((iNumber /= iBase) > 0)
{
iResult = (iNumber % iBase) * iMultiplier + iResult;
iMultiplier *= 10;
}
return iResult;
}
Code:
// A test, to see how it works
int i;
for(i = 2; i < 10; i++)
printf("123 in Base-%d: %d\n", i, GetBase(i, 123));
Code:
// Sample run
123 in Base-2: 1111011
123 in Base-3: 11120
123 in Base-4: 1323
123 in Base-5: 443
123 in Base-6: 323
123 in Base-7: 234
123 in Base-8: 173
123 in Base-9: 146
Base Conversion with 3 inputs - C
- int convert(const char *text, int inbase, int outbase);
- It breaks down the incoming text into an integer value using the inbase.
- It creates an output string based on the outbase.
Pass the function the text "43" as is. Convert the "8" and the "10" to ints however you choose -- maybe even your own atoi!
The convert function then does two things:
The second part involves div and mod operations to create the digits in outbase. Depending on how you do this, it might be easier to create this string "backwards" and then reverse it.
I hope I have mentioned enough of the basic elements to give you some sort of starting point to begin writing your coding attempt.
Number base conversion - Rosetta Code
C
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAX_OUTSTR_LEN 65
char *to_base(long num, int base)
{
static const char *map = "0123456789abcdefghijklmnopqrstuvwxyz";
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;
}
long from_base(const char *num_str, int base)
{
char *endptr;
int result = strtol(num_str, &endptr, base);
assert(*endptr == '\0'); /* if there are any characters left, then string contained invalid characters */
return result;
/* there is also strtoul() for parsing into an unsigned long */
/* in C99, there is also strtoll() and strtoull() for parsing into long long and unsigned long long, respectively */
}
Posted from Diigo. The rest of my favorite links are here.