Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
converts number to different base system (base2 - base9)
package com.lp.mysample;
import java.math.BigInteger;
/**
* @author lperumalm This class converts number to different base system (base2
* - base9)
* <h3>Sample Test Data for 16</h3>
* <ul>
* </li>
* <li>decimal-base2 for number 16 is 10000</li>
* <li>decimal-base3 for number 16 is 121</li>
* <li>decimal-base4 for number 16 is 100</li>
* <li>decimal-base5 for number 16 is 31</li>
* <li>decimal-base6 for number 16 is 24</li>
* <li>decimal-base7 for number 16 is 22</li>
* <li>decimal-base8 for number 16 is 20</li>
* <li>decimal-base9 for number 16 is 17</li>
* </ul>
*/
public class ConvertDecimalToBase2TO9 {
public static void main(String[] args) {
decimal2Base(new BigInteger("12345678900000"));
}
private static void decimal2Base(BigInteger no) {
for (int i = 2; i < 9; i++) {
BigInteger value = BigInteger.ZERO, factor = BigInteger.ONE, x = no, j = BigInteger.valueOf(i);
while (x.compareTo(BigInteger.ZERO) > 0) {
value = ((x.mod(j)).multiply(factor)).add(value);
x = x.divide(j);
factor = factor.multiply(BigInteger.TEN);
}
System.out.println("decimal-base" + i + " for number " + no + " is " + value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment