File tree Expand file tree Collapse file tree 1 file changed +11
-4
lines changed
src/main/java/com/thealgorithms/bitmanipulation Expand file tree Collapse file tree 1 file changed +11
-4
lines changed Original file line number Diff line number Diff line change @@ -24,19 +24,26 @@ private BcdConversion() {
24
24
/**
25
25
* Converts a BCD (Binary-Coded Decimal) number to binary.
26
26
* <p>Steps:
27
- * <p>1. Extract the last 4 bits (one BCD digit) from the BCD number.
28
- * <p>2. Multiply the extracted digit by the corresponding power of 10 and add it to the binary number.
29
- * <p>3. Shift the BCD number right by 4 bits to process the next BCD digit.
30
- * <p>4. Repeat steps 1-3 until the BCD number is zero.
27
+ * <p>1. Validate the BCD number to ensure all digits are between 0 and 9.
28
+ * <p>2. Extract the last 4 bits (one BCD digit) from the BCD number.
29
+ * <p>3. Multiply the extracted digit by the corresponding power of 10 and add it to the binary number.
30
+ * <p>4. Shift the BCD number right by 4 bits to process the next BCD digit.
31
+ * <p>5. Repeat steps 1-4 until the BCD number is zero.
31
32
*
32
33
* @param bcd The BCD number.
33
34
* @return The corresponding binary number.
35
+ * @throws IllegalArgumentException if the BCD number contains invalid digits.
34
36
*/
35
37
public static int bcdToBinary (int bcd ) {
36
38
int binary = 0 ;
37
39
int multiplier = 1 ;
40
+
41
+ // Validate BCD digits
38
42
while (bcd > 0 ) {
39
43
int digit = bcd & 0xF ;
44
+ if (digit > 9 ) {
45
+ throw new IllegalArgumentException ("Invalid BCD digit: " + digit );
46
+ }
40
47
binary += digit * multiplier ;
41
48
multiplier *= 10 ;
42
49
bcd >>= 4 ;
You can’t perform that action at this time.
0 commit comments