COME ON CODE ON

A blog about programming and more programming.

Convert a number from decimal base to any Base

with 6 comments

Convert a given decmal number to any other base (either positive or negative).

For example, 100 in Base 2 is 1100100 and in Base -2 is 110100100.

Here’s a simple algorithm to convert numbers from Decimal to Negative Bases :

def tonegativeBase(N,B):
   digits = []
   while i != 0:
	i, remainder = divmod (i, B)
	if (remainder < 0):
	    i, remainder = i + 1, remainder + B*-1
	digits.insert (0, str (remainder))
   return ''.join (digits)

We can just tweak the above algorithm a bit to convert a decimal to any Base. Here’s a sample code :

#include<iostream>
using namespace std;

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");
    }
}

NJOY!
-fR0DDY

Advertisements

Written by fR0DDY

February 17, 2010 at 6:06 PM

Posted in Algorithm, Maths, Programming

Tagged with , , , , ,

6 Responses

Subscribe to comments with RSS.

  1. Hey,

    Can you tell me how to publish the c++ program (sample program of yours) . Its properly formatted and coloured. I’m unable to get it 😦

    Avi Dullu

    March 21, 2010 at 10:17 AM

  2. hey, this code works really well, thanx. 😀
    p.s. * you are a genius!!!

    sib

    May 23, 2010 at 12:46 PM

  3. Beautiful Solution!

    I have question for which I am searching for an efficient solution. Can you help me with that.

    How to find the largest BST in a Binary Tree?

    Ranga

    November 9, 2010 at 2:13 AM

  4. printf(“%d”,x<0?x+(b*-1):x);

    What's the meaning of this?

    vey

    November 14, 2012 at 5:49 PM

    • See the algorithm above for negative bases.

      fR0DDY

      November 15, 2012 at 4:31 PM


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

%d bloggers like this: