Convert to integer and then sort. It is also recommended that for fields such as IP, store integers directly in the database instead of strings
Give you an example of conversion:
public long ipToLong(String ipAddress) {
long result = 0;
String[] ipAddressInArray = ipAddress.split("\.");
for (int i = 3; i >= 0; i--) {
long ip = Long.parseLong(ipAddressInArray[3 - i]);
result |= ip << (i * 8);
}
return result;
}
public String longToIp(long ip) {
StringBuilder sb = new StringBuilder(15);
for (int i = 0; i < 4; i++) {
sb.insert(0, Long.toString(ip & 0xff));
if (i < 3) {
sb.insert(0, '.');
}
ip = ip >> 8;
}
return sb.toString();
}
You can first convert the IP address to int type and then store it in the database. Or take the string in the database and convert it into a Long in Java and then compare.
The IP address consists of four parts 0-255, each part is 1Byte, and the four parts are exactly 4Byte, which is an Integer.
Postgres already has an IP type, which should be used as a field type during design
Anyway, since you mentioned this problem, just convert it into IP type and sort it
Convert to integer and then sort. It is also recommended that for fields such as IP, store integers directly in the database instead of strings
Give you an example of conversion:
You can first convert the IP address to int type and then store it in the database. Or take the string in the database and convert it into a Long in Java and then compare.
The IP address consists of four parts 0-255, each part is 1Byte, and the four parts are exactly 4Byte, which is an Integer.
shell can be sorted:
Sort in vim:
Finally, I’ll give you a python version: you can modify it in Java:
Convert it to int and then sort it
Idea: order by each field
The idea is to convert the IP into an integer and sort it: