Add Octal To Binary Converter (#4202)

This commit is contained in:
Bama Charan Chhandogi 2023-05-30 13:07:50 +05:30 committed by GitHub
parent 5d7a59654f
commit b6e78a45ac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 57 additions and 0 deletions

View File

@ -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;
}
}

View File

@ -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));
}
}