AddressUtils { public static String toCIDR(long ipA, long ipB) { int shift = 24; int routingPrefix = 32; int[] addressOctets = new int[4]; for(int i = 0; i < IP_SEGMENTS; i++) { int octetA = (int) ((ipA >> shift) % 256); int octetB = (int) ((ipB >> shift) % 256); if(octetA == octetB) { addressOctets[i] = octetA; } else { int higherOctet = Math.max(octetA, octetB); routingPrefix = Integer.numberOfLeadingZeros(higherOctet << shift); break; } shift -= 8; } String address = StringUtils.join(addressOctets, '.'); return address + '/' + routingPrefix; } private  AddressUtils(); static String longToIpv4(long ipAsLong); static long ipv4ToLong(String ipAsText); static String toCIDR(long ipA, long ipB); static long numberOfAddress(String cidrAddress);  }
@Test(dataProvider = "toCIDRDataProvider") public void toCIDR(String ipAsText, String ipBsText, String expected) { long ipA = AddressUtils.ipv4ToLong(ipAsText); long ipB = AddressUtils.ipv4ToLong(ipBsText); assertEquals(AddressUtils.toCIDR(ipA, ipB), expected); assertEquals(AddressUtils.toCIDR(ipB, ipA), expected); }