Add Octal To Binary Converter (#4202)
This commit is contained in:
parent
5d7a59654f
commit
b6e78a45ac
@ -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;
|
||||
}
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user