Java不使用系统方法实现十进制转十六进制

注意:该代码仅仅是整数之间的转换
public class Test {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
int index = sin.nextInt();

String res = "";
if (index == 0) {
System.out.println(0);
} else if (index > 0){
res = getRes(index);
} else {
index = -index;
res = "-" + getRes(index);
}
System.out.println(res);
}

public static String getRes(int index) {
String res = "";
while (index != 0) {
int t = index % 16;
if (t >= 10) {
res = (char)(t - 10 + 'A') + res;
} else {
res = t + res;
}
index = index / 16;
}
return res;
}
}
posted @ 2020-10-28 20:32  BOGY  阅读(203)  评论(0编辑  收藏  举报