From b6e78a45ac007570df4da7574b111a05000204d3 Mon Sep 17 00:00:00 2001 From: Bama Charan Chhandogi Date: Tue, 30 May 2023 13:07:50 +0530 Subject: [PATCH] Add Octal To Binary Converter (#4202) --- .../conversions/OctalToBinary.java | 42 +++++++++++++++++++ .../conversions/OctalToBinaryTest.java | 15 +++++++ 2 files changed, 57 insertions(+) create mode 100644 src/main/java/com/thealgorithms/conversions/OctalToBinary.java create mode 100644 src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java diff --git a/src/main/java/com/thealgorithms/conversions/OctalToBinary.java b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java new file mode 100644 index 00000000..711381d8 --- /dev/null +++ b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java @@ -0,0 +1,42 @@ +package com.thealgorithms.conversions; +import java.util.Scanner; + +/** + * Converts any Octal Number to a Binary Number + * + * @author Bama Charan Chhandogi + */ + +public class OctalToBinary { + public static long convertOctalToBinary(int octalNumber) { + long binaryNumber = 0; + int digitPosition = 1; + + while (octalNumber != 0) { + int octalDigit = octalNumber % 10; + long binaryDigit = convertOctalDigitToBinary(octalDigit); + + binaryNumber += binaryDigit * digitPosition; + + octalNumber /= 10; + digitPosition *= 1000; // Move to the next group of 3 binary digits + } + + return binaryNumber; + } + + public static long convertOctalDigitToBinary(int octalDigit) { + long binaryDigit = 0; + int binaryMultiplier = 1; + + while (octalDigit != 0) { + int octalDigitRemainder = octalDigit % 2; + binaryDigit += octalDigitRemainder * binaryMultiplier; + + octalDigit /= 2; + binaryMultiplier *= 10; + } + + return binaryDigit; + } +} diff --git a/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java new file mode 100644 index 00000000..6c7fe870 --- /dev/null +++ b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java @@ -0,0 +1,15 @@ +package com.thealgorithms.conversions; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +public class OctalToBinaryTest { + @Test + public void testConvertOctalToBinary() { + assertEquals(101, OctalToBinary.convertOctalToBinary(5)); + assertEquals(1001, OctalToBinary.convertOctalToBinary(11)); + assertEquals(101010, OctalToBinary.convertOctalToBinary(52)); + assertEquals(110, OctalToBinary.convertOctalToBinary(6)); + } +}