IP sorting in C Language

Source: Internet
Author: User

How to sort the IP addresses of the four fields?

Analysis:
Sorting is based on the integer of each field, and the entire IP address is a string type. Therefore, you need to read fields one by one.

Note that each field is 0 ~ 255, which can be expressed in one byte. To compare the size, the unsigned char type is used.

After reading, the most natural idea is to compare fields one by one and compare four fields in sequence, which can be called separately for sorting each field.

Considering the principle of base sorting, you may wish to use 256 as the base to implement base sorting.

Think of this, since there is such a special number 256, our fields are all the remainder of the modulo 256, We can multiply all the fields by the corresponding power of 256 according to their location; in this way, we get an integer, you only need to sort the integer. This is the same as the operating principle, that is, 256 hexadecimal. Therefore, if the operating system compares the size of the result, the result is sorted by a query. However, this method must correspond to the two by pointer or subscript.

Think of this, rememberC LanguageThe Union mechanism is provided. Definition
Union
{
Unsigned char one_ip [4];
Unsigned long four_ip;
} IP;
In this way, you can read four sub-segments with IP. one_ip and compare them with IP. four_ip. This is similar to the above, but this step is missing. It is quite concise. However, you must pay attention to the order of the fields to be read. The high field must be at the High Level. Otherwise, the comparison result is meaningless.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.