English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use functions in Java to convert binary numbers to octal numbers and vice versa.
In this program, we will first convert the binary number to decimal. Then, convert the decimal number to octal.
public class BinaryOctal { public static void main(String[] args) { long binary = 101001; int octal = convertBinarytoOctal(binary); System.out.printf("%d binary = %d octal", 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); ++; binaryNumber /= 10; } i = 1; while (decimalNumber != 0) { octalNumber += (decimalNumber % 8) * ; decimalNumber /= 8; i *= 10; } return octalNumber; } }
프로그램을 실행할 때, 출력은 다음과 같습니다:
101001 Binary = 51 Octal
이 변환은 다음과 같이 일어난다:
Binary to decimal 1 * 25 + 0 * 24 + 1 * 23 + 0 * 22 + 0 * 21 + 1 * 20 = 41 Decimal to octal 8 | 418 | 5 -- 1 8 | 0 -- 5 (51)
In this program, first convert the octal number from decimal to decimal. Then, convert the decimal number to binary.
public class OctalBinary { public static void main(String[] args) { int octal = 67; long binary = convertOctalToBinary(octal); System.out.printf("%d in octal = %d binary", 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); ++; octalNumber/=10; } i = 1; while (decimalNumber != 0) { binaryNumber += (decimalNumber % 2) * ; decimalNumber /= 2; i *= 10; } return binaryNumber; } }
프로그램을 실행할 때, 출력은 다음과 같습니다:
67 octal = 110111 2진수
이 변환은 다음과 같이 일어난다:
8진수에서 10진수로 6 * 81 + 7 * 80 = 55 10진수에서 2진수로 2 | 552 | 27 -- 1 2 | 13 -- 1 2 | 6 -- 1 2 | 3 -- 0 2 | 1 -- 1 2 | 0 -- 1 (110111)