Created
December 25, 2023 09:05
-
-
Save lobster1234/2813fe1fe7413399d07868cb34240ecf to your computer and use it in GitHub Desktop.
Java code to convert any decimal number to any base
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
public class DecimalToAnyBaseConverter { | |
/* | |
We use base 62 array for all base conversions | |
*/ | |
char[] base62 = new char[62]; | |
/* | |
The constructor just initializes the char array | |
*/ | |
private DecimalToAnyBaseConverter() { | |
//first the numbers | |
for (int i = 0; i < 10; i++) { | |
base62[i] = Character.forDigit(i, 10); | |
} | |
//next we do A through Z | |
for (int i = 10; i < 36; i++) { | |
base62[i] = (char) ('A' + i - 10); | |
} | |
//next we do a through z | |
for (int i = 36; i < 62; i++) { | |
base62[i] = (char) ('a' + i - 36); | |
} | |
} | |
private String convert(int base, long decimal) { | |
StringBuilder output = new StringBuilder(); | |
Stack<Long> stack = new Stack<>(); | |
while (true) { | |
long div = decimal / base; | |
long mod = decimal % base; | |
stack.push(mod); | |
if (div == 0) { | |
break; //this is so smelly but i am rusty | |
} else decimal = div; | |
} | |
while (!stack.isEmpty()) { | |
output.append(base62[(int) stack.pop().longValue()]); | |
} | |
return output.toString(); | |
} | |
public static void main(String[] args) { | |
new DecimalToAnyBaseConverter().test(); | |
if (args.length != 2) { | |
System.out.println("[Usage: java DecimalToAnyBaseConverter <base> <decimal>] where base is a number <= 62 and decimal is a number < 9223372036854775807."); | |
System.exit(-1); | |
} | |
try { | |
int base = Integer.parseInt(args[0]); | |
long decimal = Long.parseLong(args[1]); | |
if (base > 62) throw new IllegalArgumentException("Base cannot be > 62."); | |
System.out.println(new DecimalToAnyBaseConverter().convert(base, decimal)); | |
} catch (NumberFormatException e) { | |
System.out.println("Usage Error: both arguments need to be valid numbers."); | |
System.exit(-1); | |
} catch (IllegalArgumentException e) { | |
System.out.println("Usage Error: base cannot be > 62 [you provided " + args[0] + " ]"); | |
System.exit(-1); | |
} | |
} | |
/* | |
To run assertions pass -ea to the java command | |
*/ | |
private void test() { | |
assert new DecimalToAnyBaseConverter().convert(62, 1024).equals("GW") : "Fail"; | |
assert new DecimalToAnyBaseConverter().convert(7, 10245500).equals("153041156") : "Fail"; | |
assert new DecimalToAnyBaseConverter().convert(8, 1024).equals("2000") : "Fail"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment