Repository: TheAlgorithms/Java
Pull request #5331 (2024-08-15 21:58:18)

refactor: `BinaryToHexadecimal`
Refactoring BinaryToHexadecimal.
Adding tests for incorrect cases.

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5331?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 42.59%. Comparing base [(`a84a4a2`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/a84a4a29ed64c6e701859339d0c69d1cd5d4982c?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`1d80f6e`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/1d80f6ea58c8ec699290f69515deaa53a1399f45?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5331      +/-   ##
============================================
+ Coverage     42.56%   42.59%   +0.03%     
- Complexity     2640     2643       +3     
============================================
  Files           522      522              
  Lines         15493    15490       -3     
  Branches       2948     2950       +2     
============================================
+ Hits           6594     6598       +4     
+ Misses         8616     8609       -7     
  Partials        283      283              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5331?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/conversions/BinaryToHexadecimal.java b/src/main/java/com/thealgorithms/conversions/BinaryToHexadecimal.java
index a19baba3..9ff2f593 100644
--- a/src/main/java/com/thealgorithms/conversions/BinaryToHexadecimal.java
+++ b/src/main/java/com/thealgorithms/conversions/BinaryToHexadecimal.java
@@ -1,7 +1,7 @@
 package com.thealgorithms.conversions;
 
 import java.util.HashMap;
-import java.util.Scanner;
+import java.util.Map;
 
 /**
  * Converts any Binary Number to a Hexadecimal Number
@@ -9,52 +9,55 @@ import java.util.Scanner;
  * @author Nishita Aggarwal
  */
 public final class BinaryToHexadecimal {
+    private static final int BITS_IN_HEX_DIGIT = 4;
+    private static final int BASE_BINARY = 2;
+    private static final int BASE_DECIMAL = 10;
+    private static final int HEX_START_DECIMAL = 10;
+    private static final int HEX_END_DECIMAL = 15;
+
     private BinaryToHexadecimal() {
     }
 
     /**
-     * This method converts a binary number to a hexadecimal number.
+     * Converts a binary number to a hexadecimal number.
      *
-     * @param binary The binary number
-     * @return The hexadecimal number
+     * @param binary The binary number to convert.
+     * @return The hexadecimal representation of the binary number.
+     * @throws IllegalArgumentException If the binary number contains digits other than 0 and 1.
      */
-    static String binToHex(int binary) {
-        // hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for
-        // decimal numbers 0 to 15
-        HashMap<Integer, String> hm = new HashMap<>();
-        // String to store hexadecimal code
-        String hex = "";
-        int i;
-        for (i = 0; i < 10; i++) {
-            hm.put(i, String.valueOf(i));
-        }
-        for (i = 10; i < 16; i++) {
-            hm.put(i, String.valueOf((char) ('A' + i - 10)));
-        }
-        int currbit;
+    public static String binToHex(int binary) {
+        Map<Integer, String> hexMap = initializeHexMap();
+        StringBuilder hex = new StringBuilder();
+
         while (binary != 0) {
-            int code4 = 0; // to store decimal equivalent of number formed by 4 decimal digits
-            for (i = 0; i < 4; i++) {
-                currbit = binary % 10;
-                binary = binary / 10;
-                code4 += currbit * (int) Math.pow(2, i);
+            int decimalValue = 0;
+            for (int i = 0; i < BITS_IN_HEX_DIGIT; i++) {
+                int currentBit = binary % BASE_DECIMAL;
+                if (currentBit > 1) {
+                    throw new IllegalArgumentException("Incorrect binary digit: " + currentBit);
+                }
+                binary /= BASE_DECIMAL;
+                decimalValue += (int) (currentBit * Math.pow(BASE_BINARY, i));
             }
-            hex = hm.get(code4) + hex;
+            hex.insert(0, hexMap.get(decimalValue));
         }
-        return hex;
+
+        return !hex.isEmpty() ? hex.toString() : "0";
     }
 
     /**
-     * Main method
+     * Initializes the hexadecimal map with decimal to hexadecimal mappings.
      *
-     * @param args Command line arguments
+     * @return The initialized map containing mappings from decimal numbers to hexadecimal digits.
      */
-    public static void main(String[] args) {
-        Scanner sc = new Scanner(System.in);
-        System.out.println("Enter binary number:");
-        int binary = sc.nextInt();
-        String hex = binToHex(binary);
-        System.out.println("Hexadecimal Code:" + hex);
-        sc.close();
+    private static Map<Integer, String> initializeHexMap() {
+        Map<Integer, String> hexMap = new HashMap<>();
+        for (int i = 0; i < BASE_DECIMAL; i++) {
+            hexMap.put(i, String.valueOf(i));
+        }
+        for (int i = HEX_START_DECIMAL; i <= HEX_END_DECIMAL; i++) {
+            hexMap.put(i, String.valueOf((char) ('A' + i - HEX_START_DECIMAL)));
+        }
+        return hexMap;
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java b/src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java
index 5cbdf39a..0935701e 100644
--- a/src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java
+++ b/src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java
@@ -1,14 +1,22 @@
 package com.thealgorithms.conversions;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
-import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
 
 public class BinaryToHexadecimalTest {
 
-    @Test
-    public void testBinaryToHexadecimal() {
-        assertEquals("6A", BinaryToHexadecimal.binToHex(1101010));
-        assertEquals("C", BinaryToHexadecimal.binToHex(1100));
+    @ParameterizedTest
+    @CsvSource({"0, 0", "1, 1", "10, 2", "1111, F", "1101010, 6A", "1100, C"})
+    void testBinToHex(int binary, String expectedHex) {
+        assertEquals(expectedHex, BinaryToHexadecimal.binToHex(binary));
+    }
+
+    @ParameterizedTest
+    @CsvSource({"2", "1234", "11112"})
+    void testInvalidBinaryInput(int binary) {
+        assertThrows(IllegalArgumentException.class, () -> BinaryToHexadecimal.binToHex(binary));
     }
 }