java 进制转换工具_进制转换工具(JAVA)

/**进制转换工具,支持2-36任意进制间相互转换

*/

public class HexConverter {

public static String Quotient = null;

public static void main(String[] args) {

String a = baseConv("45435424", 10, 34);

System.out.println("10转34输出值:" + a);

System.out.println("34转10输出值:" + baseConv(a, 34, 10));

}

public static String baseConv(String in, int fr, int to) {

if (fr < 2 || fr > 36 || to < 2 || to > 36) {

return null;

}

String out = "";

Quotient = in;

while (Quotient.length() > 0) {

out = getRemainder(Quotient, fr, to) + out;

}

return out;

}

public static String getRemainder(String s, int fr, int to) {

Quotient = "";

int temp = 0;

while (s.length() > 0) {

int t = str2Int(s.substring(0, 1));

s = s.substring(1);

temp = temp * fr + t;

Quotient += int2Str(temp / to);

temp = temp % to;

}

while (Quotient.length() > 0 && Quotient.charAt(0) == '0') {

Quotient = Quotient.substring(1);

}

return int2Str(temp);

}

public static int str2Int(String s) {

return s.charAt(0) <= '9' && s.charAt(0) >= '0' ? s.charAt(0) - '0' : s

.charAt(0) - 'a' + 10;

}

public static String int2Str(int i) {

return i >= 0 && i <= 9 ? String.valueOf((char) ('0' + i)) : String

.valueOf((char) ('a' + i - 10));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值