I'm getting this IP address
00000000111111110000000011111111
I want it to display like this
00000000.11111111.00000000.11111111
This is the code I tried
String ipByte1=String.format("d", parseInt(ooct1));
String ipByte2=String.format("d", parseInt(ooct2));
String ipByte3=String.format("d", parseInt(ooct3));
String ipByte4=String.format("d", parseInt(ooct4));
//integer bitmask
int bitmask= parseInt(String.valueOf(cidr.getText()));
//32bit int from whole ip address
int ipBin= parseInt(ipByte1 ipByte2 ipByte3,2);
//32bit netmask bin
int maskBin= ~0 << (32-bitmask);
//and for network address
int netBin=ipBin & maskBin;
//or operation for Boradcast
int bcBin=ipBin | ~maskBin;
//splitting
String strIpBin =Integer.toBinaryString(ipBin);
String[] printIpBin=strIpBin.split("(?<=\\\\G........)");
bad.setText(printIpBin[0] "." printIpBin[1] "." printIpBin[2] "." printIpBin[3]);
it throws
java.lang.ArrayIndexOutOfBoundsException: length=2; index=3
CodePudding user response:
use this regex pattern: "(?<=\\G.{8})"
public static void main (String[] args)
{
String x = "00000000111111110000000011111111";
int bits = 4;
String[] results = x.split("(?<=\\G.{" bits "})");
System.out.println("L: -> " Arrays.asList(results));
}
outut:
Success #stdin #stdout 0.14s 50720KB
L: -> [0000, 0000, 1111, 1111, 0000, 0000, 1111, 1111]
CodePudding user response:
String Ip = ipByte1 "." ipByte2 "." ipByte3 "." ipByte4;
will do or else:
String myIp = "00000000111111110000000011111111";
String myIp2 = myIp.substring(0, 8 )
"." myIp.substring(8, 16)
"." myIp.substring(16, 24)
"." myIp.substring(24, 32)
;