Skip to content

Instantly share code, notes, and snippets.

@LB--
Created January 22, 2013 01:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LB--/4591371 to your computer and use it in GitHub Desktop.
Save LB--/4591371 to your computer and use it in GitHub Desktop.
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment