Convert between IPv4 and int

At present, data storage equipment is getting cheaper and cheaper, and there is no scenario where complex calculations are introduced in order to save space. However, sometimes, it is more convenient to compare and query to convert long string data such as IPv4 into numbers.

1. Direct conversion

The direct way to think of is to remove the "." between the network segments to form a long number. But in the "255.255.255.255" address, the number after removing the "." is 255255255255, which is greater than the maximum number that can be represented by int. Therefore, when it is actually used, only the long integer Long type can be used. But this approach has two serious problems:

  1. One-way conversion: It is only suitable for scenarios that require one-way conversion from IPv4 to digital. If you want to switch back, it is not easy. For example, "192.168.10.10" and "192.168.101.0" are converted into numbers of 1921681010. If you want to convert an IP address from a number, there will be ambiguity, unless it can be achieved with certain conventions.
  2. There is ambiguity after the conversion: it is also mentioned in the first article that two IP addresses are converted to get the same number. If you need to compare the IP, problems are prone to occur.

2. Shift conversion

Since the ambiguity of "." is directly removed, the 4 segments of numbers are stored separately. The value range of a segment of IPv4 is 0~255, which is 2^8 numbers. It happens that the int type occupies 32 bytes. The final result can be obtained through simple shift and or operations, and the conversion from int to IPv4 is supported.

For example: 192.168.30.68, the calculation result is:

192 << 24 | 168 << 16 | 30 << 8 | 68 = 0b11000000101010000001111001000100 = -1062724028

The reverse conversion is:

((-1062724028 >> 24) & 0xFF) + "." + ((-1062724028 >> 16) & 0xFF) + "." + ((-1062724028 >> 8) & 0xFF) + "." + (-1062724028 & 0xFF) = "192.168.30.68"

Therefore, in addition to the more troublesome calculation, the second method can perfectly solve the two problems of the first method.


Personal homepage: https://www.howardliu.cn
Personal blog post: Conversion between IPv4 and int
CSDN Homepage: http://blog.csdn.net/liuxinghao
CSDN blog post: Conversion between IPv4 and int

Guess you like

Origin blog.csdn.net/conansix/article/details/107475967