I just wrote a simple function to convert a number with any base into a base 10 number:

``````#include <stdio.h>
#include <math.h>
#include <string.h>

int tobase10(int *input, int size, int base);

int main() {
int input[256] = {2, 2, 1, 0};

printf("%d\n", tobase10(input, 4, 3));

printf("Press any key to continue ...\n");
getchar();
return 0;}

int tobase10(int *input, int size, int base) {
int result = 0;
int count = 0;

while((size+1) != 0) {
result = (input[count] * pow(base, (size-1))) + result;
count++;
size--; }
return result; }``````

I now want to modify it so it edits the input array to put every digit of the number in separate array block. Then I want it to return the number of digets there are. The only way I can think of doing this is puting the result in a string, use strlen() to get the size, and use a loop with atoi() to read it back into the input array. Is there any better, more elegant way to do this?
It seems to get ugly when I try.

3
Contributors
3
Replies
5
Views
9 Years
Discussion Span
Last Post by Hiroshe

`(int)log10(n) + 1` will give you the number of digits.
You could strip digits off with a loop body like this:

``````digit = n % 10;
// store digit or whatever
n /= 10;``````

There are two generally accepted ways to split a number into digits. First is the string conversion:

``````#include <stdio.h>

int main ( void )
{
int value;

printf ( "Enter an integer: " );
fflush ( stdout );

if ( scanf ( "%d", &value ) == 1 ) {
char buffer[50]; /* Arbitrary "large enough" size */
size_t i;

/* Quick and easy, but relatively expensive */
sprintf ( buffer, "%d", value );

for ( i = 0; buffer[i] != '\0'; i++ )
printf ( "%c\n", buffer[i] );
}

return 0;
}``````

Next is the mathematical solution, where you break the number down directly:

``````#include <stdio.h>

int main ( void )
{
int value;

printf ( "Enter an integer: " );
fflush ( stdout );

if ( scanf ( "%d", &value ) == 1 ) {
if ( value == 0 ) {
/* A typical breakdown loop doesn't handle 0 */
printf ( "0\n" );
}
else {
/* This technique works for any base */

/*
Note that the digits come in least
to most significant order
*/
while ( value != 0 ) {
printf ( "%d\n", value % radix );
}
}
}

return 0;
}``````

Most solutions are variations of these two general concepts.

Thanks alot.:) Thats plenty of info to work with.