jisan jisan - 7 months ago 21
Java Question

Printing String in ip address style

I have an array

fip[i]
which contains
[10101100, 00010000, 00001010, 00000000]
.
fip1
is taking the value in decimal one by one. Finally I would like to store the value in the
abc
variable like an IP address and print it:

172. 16. 10. 0


Code:

for(int i=0;i<4;i++)
{
fip1[i] = Integer.parseInt(fip[i],2);
if(i!=3) System.out.print(".");
}
abc = Arrays.toString(fip1);

Answer

Not 100% sure what you are asking, but if it is "how to I store the IP address value in a String", you can just use the code you already have, but replace the System.out.println statements with calls to a StringBuilder.

For example...

StringBuilder builder = new StringBuilder();

for(int i=0;i<4;i++)
   {
    builder.append(Integer.parseInt(fip[i],2));
    if(i!=3) builder.append(".");
   }

String abc = builder.toString();

System.out.println(abc); // Should print your IP address...