public
Created

  • Download Gist
BaseConvert.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
import java.math.BigInteger;
import java.io.File;
import java.io.FileOutputStream;
 
public class BaseConvert
{
public static void main(String[] args) throws Throwable
{
if(args.length < 3)
{
java.util.Scanner in = new java.util.Scanner(System.in);
System.out.println(ConvertBase(in.next(), (char)in.nextInt(), (char)in.nextInt()));
}
else if(args.length == 3)
{
System.out.println(ConvertBase(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2])));
}
else if(args.length == 4)
{
String s = ConvertBase(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]));
File f = new File(args[4]);
if(!f.exists())
{
f.createNewFile();
}
FileOutputStream ofs = new FileOutputStream(f);
ofs.write(s.getBytes());
ofs.flush();
ofs.close();
}
}
static String ConvertBase(String num, final int from, final int to)
{
if(from < 2 || from > 62 || to < 2 || to > 62) return null;
final BigInteger bi_from = new BigInteger(""+from);
final BigInteger bi_to = new BigInteger(""+to);
BigInteger n = BigInteger.ZERO;
String sign = "";
if(num.charAt(0) == '-')
{
sign = "-";
num = num.substring(1);
}
int dig = 0;
for(char c : new StringBuilder(num).reverse().toString().toCharArray())
{
int d;
if(c >= '0' && c <= '9')
{
d = c-'0';
}
else if(c >= 'A' && c <= 'Z')
{
d = c-'A'+10;
}
else if(c >= 'a' && c <= 'z')
{
d = c-'a'+36;
}
else return null;
n = n.add(bi_from.pow(dig++).multiply(new BigInteger(""+d)));
}
StringBuilder sb = new StringBuilder();
while(!n.equals(BigInteger.ZERO))
{
int d = n.mod(bi_to).intValue();
if(d >= 0 && d <= 9)
{
d = '0'+d;
}
else if(d >= 10 && d <= 35)
{
d = 'A'+d-10;
}
else
{
d = 'a'+d-36;
}
sb.append((char)d);
n = n.divide(bi_to);
}
return sign+sb.reverse();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.