Home Misc Convert a decimal number to any base.

Convert a decimal number to any base.

by nikoo28
0 comment 1 minutes read

Here is an implementation of a simple algorithm that can be used to convert any number in decimal format to a number to any other base ‘b’.

The base ‘b’ can be octal, binary or even any other arbitrary base like 7.

#include<stdio.h>
 
void convert10tob(int N,int b)
{
     if (N==0)
        return;
      
     int x = N%b;
     N/=b;
     if (x<0)
        N+=1;
         
     convert10tob(N,b);
     printf("%d",x<0?x+(b*-1):x);
     return;
}

int main()
{
    int N,b;
    while(scanf("%d%d",&N,&b)==2)
    {
          if (N!=0)
          {
              convert10tob(N,b);
              printf("\n");
          }
          else
              printf("0\n");
    }
}

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More