Advertisement
absolute100

Untitled

Apr 18th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. class Main {
  2.     public static String cidr(String ip, int num) {
  3.         String[] ipSeg = ip.split("\\.");
  4.         int total = 0;
  5.         int segNum = 1;
  6.         for (int i = ipSeg.length - 1; i >= 0; i--) {
  7.             int seg = Integer.parseInt(ipSeg[i]);
  8.             // find the highest 1 of the seg
  9.             int end = seg + num / segNum;
  10.             if (end <= 255) {
  11.                 int times = 128;
  12.                 while ((seg & times) == (end & times)) {
  13.                     total++;
  14.                     times >>= 1;
  15.                 }
  16.                 total += 8 * i;
  17.                 break;
  18.             } else {
  19.                 num = end;
  20.             }
  21.             segNum = 256;
  22.         }
  23.         return ip + "/" + total;
  24.     }
  25.  
  26.     public static void main(String[] args) {
  27.         System.out.println(cidr("1.1.1.1", 3));
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement