Repository: TheAlgorithms/Java
Pull request #5750 (2024-10-13 03:44:35)

feat: Add `IPConverter` new algorithm with Junit tests
<!--
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/5750?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 63.94%. Comparing base [(`4a03f42`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/4a03f420616a6773e9a5cdc304b1681e96d945bd?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`559d5f9`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/559d5f9c5f9250aa06b7600188d9f7b84e28d41e?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    #5750      +/-   ##
============================================
+ Coverage     63.91%   63.94%   +0.02%     
- Complexity     4167     4172       +5     
============================================
  Files           582      583       +1     
  Lines         16302    16310       +8     
  Branches       3148     3150       +2     
============================================
+ Hits          10419    10429      +10     
+ Misses         5457     5456       -1     
+ Partials        426      425       -1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5750?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/DIRECTORY.md b/DIRECTORY.md
index d9beaadc..32a084d9 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -94,6 +94,7 @@
             * [HexToOct](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/HexToOct.java)
             * [IntegerToEnglish](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java)
             * [IntegerToRoman](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java)
+            * [IPConverter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IPConverter.java)
             * [OctalToBinary](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToBinary.java)
             * [OctalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java)
             * [OctalToHexadecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java)
@@ -727,6 +728,7 @@
             * [HexToOctTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/HexToOctTest.java)
             * [IntegerToEnglishTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IntegerToEnglishTest.java)
             * [IntegerToRomanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IntegerToRomanTest.java)
+            * [IPConverterTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IPConverterTest.java)
             * [OctalToBinaryTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java)
             * [OctalToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java)
             * [OctalToHexadecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java)
diff --git a/src/main/java/com/thealgorithms/conversions/IPConverter.java b/src/main/java/com/thealgorithms/conversions/IPConverter.java
new file mode 100644
index 00000000..765cb020
--- /dev/null
+++ b/src/main/java/com/thealgorithms/conversions/IPConverter.java
@@ -0,0 +1,58 @@
+package com.thealgorithms.conversions;
+
+/**
+ * Converts an IPv4 address to its binary equivalent and vice-versa.
+ * IP to Binary: Converts an IPv4 address to its binary equivalent.
+ * Example: 127.3.4.5 -> 01111111.00000011.00000100.00000101
+ *
+ * Binary to IP: Converts a binary equivalent to an IPv4 address.
+ * Example: 01111111.00000011.00000100.00000101 -> 127.3.4.5
+ *
+ * @author Hardvan
+ */
+public final class IPConverter {
+    private IPConverter() {
+    }
+
+    /**
+     * Converts an IPv4 address to its binary equivalent.
+     * @param ip The IPv4 address to convert.
+     * @return The binary equivalent of the IPv4 address.
+     */
+    public static String ipToBinary(String ip) {
+        StringBuilder binary = new StringBuilder();
+        for (String octet : ip.split("\\.")) {
+            binary.append(octetToBinary(Integer.parseInt(octet))).append(".");
+        }
+        return binary.substring(0, binary.length() - 1);
+    }
+
+    /**
+     * Converts a single octet to its 8-bit binary representation.
+     * @param octet The octet to convert (0-255).
+     * @return The 8-bit binary representation as a String.
+     */
+    private static String octetToBinary(int octet) {
+        char[] binary = {'0', '0', '0', '0', '0', '0', '0', '0'};
+        for (int i = 7; i >= 0; i--) {
+            if ((octet & 1) == 1) {
+                binary[i] = '1';
+            }
+            octet >>>= 1;
+        }
+        return new String(binary);
+    }
+
+    /**
+     * Converts a binary equivalent to an IPv4 address.
+     * @param binary The binary equivalent to convert.
+     * @return The IPv4 address of the binary equivalent.
+     */
+    public static String binaryToIP(String binary) {
+        StringBuilder ip = new StringBuilder();
+        for (String octet : binary.split("\\.")) {
+            ip.append(Integer.parseInt(octet, 2)).append(".");
+        }
+        return ip.substring(0, ip.length() - 1);
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/conversions/IPConverterTest.java b/src/test/java/com/thealgorithms/conversions/IPConverterTest.java
new file mode 100644
index 00000000..78c226a9
--- /dev/null
+++ b/src/test/java/com/thealgorithms/conversions/IPConverterTest.java
@@ -0,0 +1,30 @@
+package com.thealgorithms.conversions;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class IPConverterTest {
+
+    private static String generateTestIP(int a, int b, int c, int d) {
+        return String.format("%d.%d.%d.%d", a, b, c, d);
+    }
+
+    private static String generateTestBinary(int a, int b, int c, int d) {
+        return String.format("%8s.%8s.%8s.%8s", Integer.toBinaryString(a), Integer.toBinaryString(b), Integer.toBinaryString(c), Integer.toBinaryString(d)).replace(' ', '0');
+    }
+
+    @Test
+    public void testIpToBinary() {
+        assertEquals(generateTestBinary(192, 168, 1, 1), IPConverter.ipToBinary(generateTestIP(192, 168, 1, 1)));
+        assertEquals(generateTestBinary(127, 3, 4, 5), IPConverter.ipToBinary(generateTestIP(127, 3, 4, 5)));
+        assertEquals(generateTestBinary(0, 0, 0, 0), IPConverter.ipToBinary(generateTestIP(0, 0, 0, 0)));
+    }
+
+    @Test
+    public void testBinaryToIP() {
+        assertEquals(generateTestIP(192, 168, 1, 1), IPConverter.binaryToIP(generateTestBinary(192, 168, 1, 1)));
+        assertEquals(generateTestIP(127, 3, 4, 5), IPConverter.binaryToIP(generateTestBinary(127, 3, 4, 5)));
+        assertEquals(generateTestIP(0, 0, 0, 0), IPConverter.binaryToIP(generateTestBinary(0, 0, 0, 0)));
+    }
+}