chosen_base_to_chosen_base.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import flanagan.io.KeyboardInput;
  2. import java.math.BigInteger;
  3. import java.lang.Math;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. public class chosen_base_to_chosen_base {
  7. public static void main(String arg[]) {
  8. KeyboardInput kb = new KeyboardInput();
  9. String input_number = kb.readLine("input number =");
  10. BigInteger input_base = kb.readBigInteger("input base =");
  11. BigInteger output_base = kb.readBigInteger("output base =");
  12. BigInteger current_number, decimal_number = BigInteger.ZERO;
  13. String chartable = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  14. /* exit when one of the chosen bases is too big for the chartable */
  15. if (input_base.compareTo(BigInteger.valueOf(chartable.length())) == 1 ||
  16. output_base.compareTo(BigInteger.valueOf(chartable.length())) == 1 ) {
  17. System.out.println("Error: chosen base was out too big in " +
  18. "respect to the chartable defined by this program");
  19. System.exit(1);
  20. }
  21. /* calc decimal number */
  22. for (int i = 0; i < input_number.length(); i++) {
  23. current_number = BigInteger.valueOf(chartable.indexOf(
  24. input_number.substring(i,i + 1)));
  25. /* exit when digit is bigger than base allows */
  26. if (input_base.compareTo(current_number) < 1 ) {
  27. System.out.println("Error: Nonsensical input. Plase make sure " +
  28. "not to use digits bigger than the base allows");
  29. System.exit(1);
  30. }
  31. decimal_number = decimal_number.add(current_number.multiply(
  32. input_base.pow(input_number.length() - i - 1)));
  33. }
  34. ArrayList<Character> remainders = new ArrayList<Character>();
  35. String output_number = "";
  36. /* calculate remainders */
  37. while(decimal_number.compareTo(BigInteger.ZERO) > 0){
  38. remainders.add(chartable.charAt(decimal_number.mod(output_base).intValue()));
  39. decimal_number = decimal_number.divide(output_base);
  40. }
  41. /* reverse remainders to get the output number */
  42. for (int i = 1;i <= remainders.size(); i++){
  43. output_number += remainders.get(remainders.size()-i);
  44. }
  45. System.out.println(output_number);
  46. System.out.printf("length: %d\n", output_number.length());
  47. System.exit(0);
  48. }
  49. }