算法题(三):十六进制十进制间的相互转换
程序员文章站
2024-03-16 22:22:22
...
//十六进制转成十进制
public static void fun1(String str) {
if(str==null || str.length()<2 || "0x".equals(str.substring(0, 1))) {
return;
}
String nums = str.substring(2);
System.out.println(nums);
int result = 0;
for(int i=0; i<nums.length(); i++) {
if(nums.charAt(i) >='0' && nums.charAt(i)<='9') {
int temp = nums.charAt(i) - '0';
result = result*16+temp;
}else if(nums.charAt(i)>='a' && nums.charAt(i)<='z') {
int temp = nums.charAt(i) - 'a'+10;
result = result*16+temp;
}else if(nums.charAt(i)>='A' && nums.charAt(i)<='Z') {
int temp = nums.charAt(i) - 'A'+10;
result = result*16+temp;
}
}
System.out.println(result);
}
//十进制转成十六进制
public static void fun2(int number) {
Stack<Integer> stack = new Stack<>();
String res = "0x";
while(number!=0) {
stack.push(number%16);
number = number/16;
}
while(!stack.isEmpty()) {
res += stack.pop();
}
System.out.println(res);
}