在此程序中,您將學(xué)習(xí)使用Java中的函數(shù)將二進(jìn)制數(shù)轉(zhuǎn)換為八進(jìn)制數(shù),反之亦然。
在此程序中,我們將首先將二進(jìn)制數(shù)字轉(zhuǎn)換為十進(jìn)制。然后,十進(jìn)制數(shù)字轉(zhuǎn)換為八進(jìn)制。
public class BinaryOctal {
public static void main(String[] args) {
long binary = 101001;
int octal = convertBinarytoOctal(binary);
System.out.printf("%d 二進(jìn)制 = %d 八進(jìn)制", binary, octal);
}
public static int convertBinarytoOctal(long binaryNumber)
{
int octalNumber = 0, decimalNumber = 0, i = 0;
while(binaryNumber != 0)
{
decimalNumber += (binaryNumber % 10) * Math.pow(2, i);
++i;
binaryNumber /= 10;
}
i = 1;
while (decimalNumber != 0)
{
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}
}運(yùn)行該程序時(shí),輸出為:
101001 二進(jìn)制 = 51 八進(jìn)制
此轉(zhuǎn)換發(fā)生為:
二進(jìn)制到十進(jìn)制 1 * 25 + 0 * 24 + 1 * 23 + 0 * 22 + 0 * 21 + 1 * 20 = 41 十進(jìn)制到八進(jìn)制 8 | 418 | 5 -- 1 8 | 0 -- 5 (51)
在此程序中,首先將八進(jìn)制數(shù)從十進(jìn)制轉(zhuǎn)換為十進(jìn)制。然后,將十進(jìn)制數(shù)轉(zhuǎn)換為二進(jìn)制數(shù)。
public class OctalBinary {
public static void main(String[] args) {
int octal = 67;
long binary = convertOctalToBinary(octal);
System.out.printf("%d in octal = %d 二進(jìn)制", octal, binary);
}
public static long convertOctalToBinary(int octalNumber)
{
int decimalNumber = 0, i = 0;
long binaryNumber = 0;
while(octalNumber != 0)
{
decimalNumber += (octalNumber % 10) * Math.pow(8, i);
++i;
octalNumber/=10;
}
i = 1;
while (decimalNumber != 0)
{
binaryNumber += (decimalNumber % 2) * i;
decimalNumber /= 2;
i *= 10;
}
return binaryNumber;
}
}運(yùn)行該程序時(shí),輸出為:
67 in octal = 110111 二進(jìn)制
此轉(zhuǎn)換發(fā)生為:
八進(jìn)制到十進(jìn)制 6 * 81 + 7 * 80 = 55 十進(jìn)制到二進(jìn)制 2 | 552 | 27 -- 1 2 | 13 -- 1 2 | 6 -- 1 2 | 3 -- 0 2 | 1 -- 1 2 | 0 -- 1 (110111)