Skip to content

Commit b6e78a4

Browse files
Add Octal To Binary Converter (TheAlgorithms#4202)
1 parent 5d7a596 commit b6e78a4

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.thealgorithms.conversions;
2+
import java.util.Scanner;
3+
4+
/**
5+
* Converts any Octal Number to a Binary Number
6+
*
7+
* @author Bama Charan Chhandogi
8+
*/
9+
10+
public class OctalToBinary {
11+
public static long convertOctalToBinary(int octalNumber) {
12+
long binaryNumber = 0;
13+
int digitPosition = 1;
14+
15+
while (octalNumber != 0) {
16+
int octalDigit = octalNumber % 10;
17+
long binaryDigit = convertOctalDigitToBinary(octalDigit);
18+
19+
binaryNumber += binaryDigit * digitPosition;
20+
21+
octalNumber /= 10;
22+
digitPosition *= 1000; // Move to the next group of 3 binary digits
23+
}
24+
25+
return binaryNumber;
26+
}
27+
28+
public static long convertOctalDigitToBinary(int octalDigit) {
29+
long binaryDigit = 0;
30+
int binaryMultiplier = 1;
31+
32+
while (octalDigit != 0) {
33+
int octalDigitRemainder = octalDigit % 2;
34+
binaryDigit += octalDigitRemainder * binaryMultiplier;
35+
36+
octalDigit /= 2;
37+
binaryMultiplier *= 10;
38+
}
39+
40+
return binaryDigit;
41+
}
42+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.thealgorithms.conversions;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class OctalToBinaryTest {
8+
@Test
9+
public void testConvertOctalToBinary() {
10+
assertEquals(101, OctalToBinary.convertOctalToBinary(5));
11+
assertEquals(1001, OctalToBinary.convertOctalToBinary(11));
12+
assertEquals(101010, OctalToBinary.convertOctalToBinary(52));
13+
assertEquals(110, OctalToBinary.convertOctalToBinary(6));
14+
}
15+
}

0 commit comments

Comments
 (0)