|
| 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 | +} |
0 commit comments