十进制转八进制
例子:
输入: 10
输出: 12
思路:对8进行取模运算并存入栈,直至该数字为0,将栈输出
public static void Dex2Oct(int num){
if (num < 8){
System.out.println("转换后的八进制数为:"+ num);
}
int i;
Stack<Integer> stack = new Stack<>();
while (num > 0){
i = num % 8;
stack.push(i);
num /= 8;
}
while (stack.size() > 0){
Integer pop = stack.pop();
System.out.format("%d",pop);
}
}
十六进制转八进制 先将十六进制转为十进制,再将十进制转为八进制
方法:从末尾遍历字符串,权值为0,倒数第二位权值为16,第三位为16*16,依次。。。
使用Math.pow(16,index),index代表权值
public static void Hex2Oct(String n){
//位数
int reIndex = 0, dexVal = 0;
for (int i = n.length() - 1; i >= 0; i--) {
if (Character.isDigit(n.charAt(i)) &&
Integer.parseInt(String.valueOf(n.charAt(i))) >=0 &&
Integer.parseInt(String.valueOf(n.charAt(i))) <=9){
dexVal += Integer.parseInt(String.valueOf(n.charAt(i))) * Math.pow(16,reIndex);
}else{
switch (n.charAt(i)){
case 'A':
//权值*该位上的数字值
dexVal += 10 * Math.pow(16,reIndex);
break;
case 'B':
dexVal += 11 * Math.pow(16,reIndex);
break;
case 'C':
dexVal += 12 * Math.pow(16,reIndex);
break;
case 'D':
dexVal += 13 * Math.pow(16,reIndex);
break;
case 'E':
dexVal += 14 * Math.pow(16,reIndex);
break;
case 'F':
dexVal += 15 * Math.pow(16,reIndex);
break;
}
}
reIndex ++;
}
//调用上述十进制转八进制
Dex2Oct(dexVal);
}