You need to understand binary numbers, nothing more.
A CIDR block is nothing more than a series of binary numbers with a common prefix and all possible suffixes. Assume for example below, there were 8-bit IP addresses, with classes /1 , ... to /8 .
In your case (ignoring 1.1.1 now), we write your numbers as binary numbers:
1101111 - 111 1110000 - 112 1110001 - 113 ... 1110110 - 118 1110111 - 119 1111000 - 120
You will see that all numbers have a common prefix of 11 , but our list does not contain all of these numbers. Therefore, we must break it into two lists: one with 110 and one with 111 . The first contains only one number, so we make from it /8 block ( 111/8 ).
The other list (from 112 to 120) does not contain all the numbers from 111 (since then it will go up to 127), so we will again divide one list from 1110 , the other from 1111 . The first is now complete block 1110???? (or 112/4 ), the second - only one address, namely 11111000 (or 120/8 ).
So, now we only expand to 32 bits instead of 8 and implement it in Java, and you are ready.
In mathematical terms, one block always goes from x * 2 ^ n to (x + 1) * 2 ^ n - 1 , and then we use 32 - n as the suffix of the block size. Therefore, you only need to find the next multiple of some power of two.
source share