## Convert a number from decimal base to any Base

**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

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 DulluMarch 21, 2010 at 10:17 AM

You do not need any plugins to do that. Just have a look at the support section. More precisely http://en.support.wordpress.com/code/ for code syntax highlighter and http://en.support.wordpress.com/latex/ for latex.

fR0DDYMarch 22, 2010 at 10:42 AM

hey, this code works really well, thanx. 😀

p.s. * you are a genius!!!

sibMay 23, 2010 at 12:46 PM

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?

RangaNovember 9, 2010 at 2:13 AM

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

What's the meaning of this?

veyNovember 14, 2012 at 5:49 PM

See the algorithm above for negative bases.

fR0DDYNovember 15, 2012 at 4:31 PM