php中的ip2long和long2ip的理解

IPv4地址是如何表示的

IPv4使用无符号32位地址,因此最多有2的32次方减1(4294967295)个地址。一般的书写法为用4个小数点分开的十进制数,记为:A.B.C.D,比如:157.23.56.90。

IPv4地址转换成无符号整型

右移

逻辑右移

右移多少位,则在高位补多少位0。

算术右移

对无符号数做算术右移和逻辑右移的结果是相同的。但是对一个有符号数做算术右移,则右移多少位,即在高位补多少位1。

注意事项

对于C来说,只提供了>>右移运算符,究竟是逻辑右移还是算术右移这取决于编译器的行为,因此一般只提倡对无符号数进行位操作。

#include <stdio.h>
#include <time.h>

unsigned int ip2long(const char *ip){
        unsigned int a, b, c, d;
        unsigned int ret;
        int num = sscanf(ip, "%d.%d.%d.%d", &a, &b, &c, &d);
        if(num == 4){
                ret = (a << 24) + (b << 16) + (c << 8) + d;
        }else{
                ret = 0;
        }
        return ret;
}

int long2ip(unsigned int intip, char *str, int str_len){
        if(!str){
                return -1;
        }
        int a, b, c, d;
        a = (intip & 0xff000000) >> 24;
        b = (intip & 0x00ff0000) >> 16;
        c = (intip & 0x0000ff00) >> 8;
        d = intip & 0x000000ff;
        snprintf(str, str_len, "%d.%d.%d.%d", a, b, c, d);
        return 0;
}

int main(){
        const char *ip = "222.234.255.189";
        unsigned ret;

        ret = ip2long(ip);
        printf("ip2long=%u
", ret);

        char str[512];
        long2ip(ret, str, sizeof(str));
        printf("long2ip=%s
", str);
}

关于位运算有一片非常好的文章:http://blog.csdn.net/hguisu/article/details/7892596

原文地址:https://www.cnblogs.com/bai-jimmy/p/5414157.html