File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
main/java/com/thealgorithms/conversions
test/java/com/thealgorithms/conversions Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .thealgorithms .conversions ;
2+
3+ /**
4+ * Converts an IPv4 address to its binary equivalent and vice-versa.
5+ * IP to Binary: Converts an IPv4 address to its binary equivalent.
6+ * Example: 127.3.4.5 -> 01111111.00000011.00000100.00000101
7+ *
8+ * Binary to IP: Converts a binary equivalent to an IPv4 address.
9+ * Example: 01111111.00000011.00000100.00000101 -> 127.3.4.5
10+ *
11+ * @author Hardvan
12+ */
13+ public final class IPConverter {
14+ private IPConverter () {
15+ }
16+
17+ public static String ipToBinary (String ip ) {
18+ StringBuilder binary = new StringBuilder ();
19+ for (String octet : ip .split ("\\ ." )) {
20+ binary .append (String .format ("%08d" , Integer .parseInt (Integer .toBinaryString (Integer .parseInt (octet ))))).append ("." );
21+ }
22+ return binary .substring (0 , binary .length () - 1 );
23+ }
24+
25+ public static String binaryToIP (String binary ) {
26+ StringBuilder ip = new StringBuilder ();
27+ for (String octet : binary .split ("\\ ." )) {
28+ ip .append (Integer .parseInt (octet , 2 )).append ("." );
29+ }
30+ return ip .substring (0 , ip .length () - 1 );
31+ }
32+ }
Original file line number Diff line number Diff line change 1+ package com .thealgorithms .conversions ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertEquals ;
4+
5+ import org .junit .jupiter .api .Test ;
6+
7+ public class IPConverterTest {
8+
9+ @ Test
10+ public void testIpToBinary () {
11+ assertEquals ("11000000.10101000.00000001.00000001" , IPConverter .ipToBinary ("192.168.1.1" ));
12+ assertEquals ("01111111.00000011.00000100.00000101" , IPConverter .ipToBinary ("127.3.4.5" ));
13+ }
14+
15+ @ Test
16+ public void testBinaryToIP () {
17+ assertEquals ("192.168.1.1" , IPConverter .binaryToIP ("11000000.10101000.00000001.00000001" ));
18+ assertEquals ("127.3.4.5" , IPConverter .binaryToIP ("01111111.00000011.00000100.00000101" ));
19+ }
20+ }
You can’t perform that action at this time.
0 commit comments