Convert from decimal to base-n number system and vice versa

Convert from decimal to base-n number system
We can implement this with a simple, easy to understand program:

void g( int x, int n ) {
    if ( x ) {
        g( x / n, n );
        std::cout << x % n;
    }
}


Convert from decimal to base-n number system
Let’s  consider an example converting a binary number to decimal number:
10101_(2) = 2^4 * 1 + 2^3 * 0 + 2^2 * 1 + 2^1 * 0 + 2^0 * 1
We also can write it like this:
10101_(2) = 1 + 2 * ( 0 + 2 * ( 1 + 2 * ( 0 + 2 * 1 ) ) )

Expanding for base-n number system, if we have a number in base-n number system: c_{0}c_{1}...c_{m-1}( n )
Then:
c_{0}c_{1}...c_{m-1}( n ) = c_{m-1} + n * ( c_{m-2} + n * ( ... n * c_{0} ) ..
Finally we have a program without the need of pow function:

int h( char * src, int n ) {
    int decimal = 0;
    for( char * p = src; p - src < strlen( src ); p++ ) {
        decimal = decimal * n + *p - '0';
    }

    return decimal;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s