在此程序中,您將學(xué)習(xí)如何使用Java中的函數(shù)將八進(jìn)制數(shù)轉(zhuǎn)換為十進(jìn)制數(shù),反之亦然。
public class DecimalOctal {
public static void main(String[] args) {
int decimal = 78;
int octal = convertDecimalToOctal(decimal);
System.out.printf("%d 十進(jìn)制 = %d 八進(jìn)制", decimal, octal);
}
public static int convertDecimalToOctal(int decimal)
{
int octalNumber = 0, i = 1;
while (decimal != 0)
{
octalNumber += (decimal % 8) * i;
decimal /= 8;
i *= 10;
}
return octalNumber;
}
}運行該程序時,輸出為:
78 十進(jìn)制 = 116 八進(jìn)制
此轉(zhuǎn)換發(fā)生為:
8 | 788 | 9 -- 6 8 | 1 -- 1 8 | 0 -- 1 (116)
public class OctalDecimal {
public static void main(String[] args) {
int octal = 116;
int decimal = convertOctalToDecimal(octal);
System.out.printf("%d 八進(jìn)制 = %d十進(jìn)制", octal, decimal);
}
public static int convertOctalToDecimal(int octal)
{
int decimalNumber = 0, i = 0;
while(octal != 0)
{
decimalNumber += (octal % 10) * Math.pow(8, i);
++i;
octal/=10;
}
return decimalNumber;
}
}運行該程序時,輸出為:
116 八進(jìn)制 = 78 十進(jìn)制
此轉(zhuǎn)換發(fā)生為:
1 * 82 + 1 * 81 + 6 * 80 = 78