Java code to convert from Base-10 to Base-9

Emil picture Emil · Oct 8, 2010 · Viewed 11.1k times · Source

How to convert a long number in base 10 to base 9 without converting to string ?

Answer

MAK picture MAK · Oct 8, 2010

FWIW, all values are actually in base 2 inside your machine (I bet you already knew that). It only shows up as base 10 because string conversion creates string representations in base 10 (e.g. when you print), because methods like parseLong assumes the input string is in base 10 and because the compiler expects all literals to be in base 10 when you actually write code. In other words, everything is in binary, the computer only converts stuff into and from base 10 for the convenience of us humans.

It follows that we should be easily able to change the output base to be something other than 10, and hence get string representations for the same value in base 9. In Java this is done by passing an optional extra base parameter into the Long.toString method.

long x=10;
System.out.println(Long.toString(x,9));