package com.thealgorithms.conversions; /** * Utility class for converting hexadecimal numbers to binary representation. *

* A hexadecimal number consists of digits from {@code [0-9]} and {@code [A-F]} (case-insensitive), * while binary representation uses only {@code [0, 1]}. *

* This class provides methods to: *

*

* Example: *

* *

This class assumes that the input hexadecimal string is valid.

*/ public class HexaDecimalToBinary { /** * Converts a hexadecimal string to its binary string equivalent. * The binary output is padded to a minimum of 8 bits (1 byte). * Steps: *
    *
  1. Convert the hexadecimal string to an integer.
  2. *
  3. Convert the integer to a binary string.
  4. *
  5. Pad the binary string to ensure it is at least 8 bits long.
  6. *
  7. Return the padded binary string.
  8. *
* * @param numHex the hexadecimal string (e.g., "A1", "7F") * @throws NumberFormatException if the input string is not a valid hexadecimal number * @return the binary string representation, padded to 8 bits (e.g., "10100001") */ public String convert(String numHex) { int conHex = Integer.parseInt(numHex, 16); String binary = Integer.toBinaryString(conHex); return completeDigits(binary); } /** * Pads the binary string to ensure it is at least 8 bits long. * If the binary string is shorter than 8 bits, it adds leading zeros. * * @param binNum the binary string to pad * @return the padded binary string with a minimum length of 8 */ public String completeDigits(String binNum) { final int byteSize = 8; StringBuilder binNumBuilder = new StringBuilder(binNum); while (binNumBuilder.length() < byteSize) { binNumBuilder.insert(0, "0"); } binNum = binNumBuilder.toString(); return binNum; } }