Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 768
Emil Avatar asked Nov 27 '22 23:11

Emil


2 Answers

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));
like image 93
MAK Avatar answered Dec 09 '22 19:12

MAK


Long base10 = 10;
Long.valueOf(base10.toString(), 9);
like image 23
mR_fr0g Avatar answered Dec 09 '22 18:12

mR_fr0g