Javascript converts IP addresses to numeric values to challenge efficiency.

Source: Internet
Author: User
Document directory
  • Why do I need to convert an IP address:
First look at what is an IP Address:

The IP address is a 32-bit binary number, which is usually divided into four "8-bit binary numbers" (4 bytes ). IP addresses are usually expressed in the form of (A. B. C. D), where, A, B, C, and D are all 0 ~ A decimal integer between 255. For example, the IP address 100.4.5.6 is actually a 32-bit binary number (01100100.00000100.00000101.00000110 ).

Why do I need to convert an IP address:

The dot-decimal notation is only intended for good memory and cannot be used in computer operations;

Some fields in the database and IP addresses are generally stored as integers, which facilitates query and improves the query speed;

Several conversion schemes in javascript:

First, let's talk about IP address verification,

The regular expression is used for verification. The expression is as follows:

var REG =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;

Reg is used later in the Code. Although this regular expression is a bit long, it can be used to verify and split the verification step in place, and the process of splitting the IP address is omitted during subsequent conversion;

Solution 1: convert every eight digits into hexadecimal characters and then splice them into integers.

When the IP address passes the ". after the split, each segment should be 8 bits, so we can convert it into two hexadecimal numbers, splice the hexadecimal string, and convert it into numbers.

 
function ipToInt(IP){    var xH = "",result = REG.exec(ip);    if(!result) return -1;    for (var i = 1; i <= 4; i++) {        var h = parseInt(result[i]);        xH += (h > 15 ? "" : "0") + h.toString(16);    }    return parseInt(xH, 16);}

If you don't want to verify it, you can use a more handsome way:

function ipToInt(IP){    return parseInt(IP.replace(/\d+\.?/ig,function(a){        a = parseInt(a);         return (a > 15 ? "" : "0") + a.toString(16);    }),16);}
Solution 2: Direct computing

Knowing the structure of the IP address makes it hard to multiply the number after the split by the corresponding number;

function ipToInt(IP){    var xH = "",result = REG.exec(ip);    if(!result) return -1;    return (parseInt(result[1]) * 0x1000000         + parseInt(result[2]) * 0x10000         + parseInt(result[3]) * 0x100         + parseInt(result[4]));}
Solution 3: Calculate by bit

Direct computation is not as good as bitwise computation. Isn't it faster?

function ipToInt(IP){    var xH = "",result = REG.exec(ip);    if(!result) return -1;    return (parseInt(result[1]) << 24         | parseInt(result[2]) << 16        | parseInt(result[3]) << 8        | parseInt(result[4]));}

If you do not understand it, please go back and complete the 2-digit course.

The bitwise operation above seems no problem,
After trying several IP addresses, I found that the IP address is incorrect. When the IP address value is greater than 0x7fffffff (127.00000000255), it becomes a negative number.
The reason is that JavaScript is regarded as a 32-bit integer during bitwise operations. Originally, it was just 32 bits. The leftmost bit of the result is a symbol bit, which is not enough.
Is it true that many of you have abandoned this security case after discovering the overflow.

When I was about to give up, I thought, no, isn't the symbol bit 0, 1, or ">>>" unsigned right shift operator, I can't move the value 0 to the right without a symbol:

function ipToInt(IP){    var xH = "",result = REG.exec(ip);    if(!result) return -1;    return (parseInt(result[1]) << 24         | parseInt(result[2]) << 16        | parseInt(result[3]) << 8        | parseInt(result[4]))>>>0;}

After the test, it was OK. Fortunately, the IP address is 32 bits. Otherwise, this solution can only be abandoned.

Solution 4: Combine the bitwise AND String concatenation (purely confused)
function ipToInt(IP) {    var xH = "",    result = REG.exec(ip);    if (!result) return - 1;    var ip2 = "000000" + ((parseInt(result[2]) << 16) | (parseInt(result[3]) << 8) | parseInt(result[4])).toString(16);    return parseInt(parseInt(result[1]).toString(16) + ip2.substr(ip2.length - 6), 16);}

You must be asking why there is such a strange idea. In fact, the question of the symbol bit in the ambit operation is unwilling to give up. This is the idea.

Summary

In principle, solution 3 is the most efficient method.
However, the last 1 million computation tests show that the efficiency of solution 2 is almost the same as that of solution 3. Is it because of V8?

Attach an inverse function:

function intToIp(INT){    if(INT < 0 || INT > 0xFFFFFFFF){        throw ("The number is not normal!");    }    return (INT>>>24) + "." + (INT>>16 & 0xFF) + "." + (INT>>8 & 0xFF) + "." + (INT & 0xFF);}

Reprinted please indicate the source http://www.cnblogs.com/whyoopThank you!

 

Related Article

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.