Skip to content

Commit bdfa5f1

Browse files
committed
Fix
1 parent 0cef808 commit bdfa5f1

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/main/java/com/thealgorithms/conversions/IPConverter.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,27 @@ private IPConverter() {
2222
public static String ipToBinary(String ip) {
2323
StringBuilder binary = new StringBuilder();
2424
for (String octet : ip.split("\\.")) {
25-
binary.append(String.format("%8s", Integer.toBinaryString(Integer.parseInt(octet))).replace(' ', '0')).append(".");
25+
binary.append(octetToBinary(Integer.parseInt(octet))).append(".");
2626
}
2727
return binary.substring(0, binary.length() - 1);
2828
}
2929

30+
/**
31+
* Converts a single octet to its 8-bit binary representation.
32+
* @param octet The octet to convert (0-255).
33+
* @return The 8-bit binary representation as a String.
34+
*/
35+
private static String octetToBinary(int octet) {
36+
char[] binary = {'0', '0', '0', '0', '0', '0', '0', '0'};
37+
for (int i = 7; i >= 0; i--) {
38+
if (octet % 2 == 1) {
39+
binary[i] = '1';
40+
}
41+
octet /= 2;
42+
}
43+
return new String(binary);
44+
}
45+
3046
/**
3147
* Converts a binary equivalent to an IPv4 address.
3248
* @param binary The binary equivalent to convert.

0 commit comments

Comments
 (0)