# IP Address to IP Number (and back)

Version 2

Description:

IP Addresses typically appear as four numbers delimited by periods, i.e. 123.4.56.78. Sometimes, however, an equivalent form known as an IP number is used the IP Number is a single integer. This is common in lookup tables, since in most programming situations it is easier to do comparisons with a simple integer. Conceptually the conversion between these two is simple, since the IP address is actually just a 4 digit number in base 256 (with the digits separated by periods).

Converting the IP address above to an IP number is 123*256^3+4*256^2+56*256+78 = 2063874126

The main challenge in execution is parsing the individual digits from the IP address from string form, since each base 256 digit may be 1, 2 or 3 decimal digits.

For completeness I also included the calculation in the other direction. The modulo operator % is the remainder term in integer division, it makes for a convenient way to change base.

From IP Address to IP Number:

//First compute the location of the delimiters, these are easiest to implement as 3 separate calculations.

//Delimiter1

//Delimiter2

//Delimiter2

//Once the delimiter positions are known, they can be used to parse out individual base 256 digits.

//IP Number

From IP Number to IP Address:

//Again, several calculations are used, first to create the individual digits, then to form the IP Address as a string

//Digit1

int([IP_Number]/256^3)%256

//Digit2

int([IP_Number]/256^2)%256

//Digit3

int([IP_Number]/256)%256

//Digit4

[IP_Number]%256