【1】十进制转十六进制
思路:每次对数字进行取余,判断余数是否大于等于10【大于等于10的用字母表示】,然后取整;
代码如下:
//十进制 转 十六进制
public class DecToHex {
public static void main(String[] args) {
int num = 654321;
ArrayStack<String> stack = new ArrayStack<>();//有字母有数字
int temp;
while(num != 0){
temp = num % 16;
num /= 16;
if(temp < 10){
stack.push(temp + " ");
}else {
stack.push(((char)('A' + (temp - 10)) + " "));
}
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
System.out.println(sb);
}
}
【2】十六进制转十进制
思路:遍历字符串,判断是数字还是字母,分别进行讨论
代码如下:
//十六进制 转 十进制
public class HexToDec {
public static void main(String[] args) {
String hex = "9FBF1";
ArrayStack<Character> stack = new ArrayStack<Character>();
for(int i = 0; i < hex.length(); i++){
stack.push(hex.charAt(i));
}
int sum = 0;
int power = 0;//幂
char c;
while(!stack.isEmpty()){
c = stack.pop();
sum += getNumber(c) * Math.pow(16,power++);
}
System.out.println(sum);
}
private static int getNumber(char c) {
if(!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F')){
throw new IllegalArgumentException("wrong char!");
}
if(c >= '0' && c <= '9'){
return c - '0';
}else{
return c - 'A' + 10;
}
}
}