Write a C progam to convert from decimal to any base (binary, hex, oct etc…)

Here is some really cool C code

#include <stdio.h>

int main()
{
decimal_to_anybase(10, 2);
decimal_to_anybase(255, 16);
getch();
}

decimal_to_anybase(int n, int base)
{
int i, m, digits[1000], flag;
i=0;

printf(“\n\n[%d] converted to base [%d] : “, n, base);

while(n)
{
m=n%base;
digits[i]=”0123456789abcdefghijklmnopqrstuvwxyz”[m];
n=n/base;
i++;
}

//Eliminate any leading zeroes
for(i–;i>=0;i–)
{
if(!flag && digits[i]!=’0′)flag=1;
if(flag)printf(“%c”,digits[i]);
}
}

Advertisements

3 thoughts on “Write a C progam to convert from decimal to any base (binary, hex, oct etc…)

  1. This really is interesting, You are a incredibly knowledgeable digg. I’ve got become a member of ones rss feed and look toward looking for extra of this great publish. In addition, We’ve shared your site during my myspace

  2. gaurav says:

    hi raja,
    whats this line does in your code

    digits[i]=”0123456789abcdefghijklmnopqrstuvwxyz”[m];

    why you have used [m] like that..??

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