Skip to content

Commit e22634e

Browse files
committed
feat: Add BCDConverter new algorithm with Junit tests
1 parent 4a03f42 commit e22634e

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.thealgorithms.conversions;
2+
3+
/**
4+
* Provides methods to convert between Decimal and Binary Coded Decimal (BCD).
5+
* Decimal to BCD: Each decimal digit is converted to its 4-bit binary equivalent.
6+
* Example: 123 -> 0001 0010 0011
7+
*
8+
* BCD to Decimal: Each 4-bit binary number is converted to its decimal equivalent.
9+
* Example: 0001 0010 0011 -> 123
10+
*
11+
* Applications: Used in digital systems like calculators and clocks.
12+
*
13+
* @author Hardvan
14+
*/
15+
public final class BCDConverter {
16+
private BCDConverter() {
17+
}
18+
19+
/**
20+
* Converts a decimal number to its BCD (Binary Coded Decimal) representation.
21+
* @param number the decimal number to be converted.
22+
* @return the BCD as a String.
23+
*/
24+
public static String decimalToBCD(int number) {
25+
StringBuilder bcd = new StringBuilder();
26+
while (number > 0) {
27+
int digit = number % 10;
28+
bcd.insert(0, String.format("%04d", Integer.parseInt(Integer.toBinaryString(digit))));
29+
number /= 10;
30+
}
31+
return bcd.toString();
32+
}
33+
34+
/**
35+
* Converts a BCD string back to its decimal representation.
36+
* @param bcd the BCD string to convert.
37+
* @return the decimal number as an integer.
38+
*/
39+
public static int bcdToDecimal(String bcd) {
40+
int decimal = 0;
41+
for (int i = 0; i < bcd.length(); i += 4) {
42+
String digitBinary = bcd.substring(i, i + 4);
43+
decimal = decimal * 10 + Integer.parseInt(digitBinary, 2);
44+
}
45+
return decimal;
46+
}
47+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.thealgorithms.conversions;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class BCDConverterTest {
8+
9+
@Test
10+
public void testDecimalToBCD() {
11+
assertEquals("00010010", BCDConverter.decimalToBCD(12));
12+
assertEquals("001001000011", BCDConverter.decimalToBCD(243));
13+
}
14+
15+
@Test
16+
public void testBCDToDecimal() {
17+
assertEquals(12, BCDConverter.bcdToDecimal("00010010"));
18+
assertEquals(243, BCDConverter.bcdToDecimal("001001000011"));
19+
}
20+
}

0 commit comments

Comments
 (0)