大家好,欢迎来到IT知识分享网。
IPv4地址是如何表示的
IPv4使用无符号32位地址,因此最多有2的32次方减1()个地址。一般的书写法为用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\n", ret); char str[512]; long2ip(ret, str, sizeof(str)); printf("long2ip=%s\n", str); }
关于位运算有一片非常好的文章:php中的ip2long和long2ip的理解
转载于:https://www.cnblogs.com/bai-jimmy/p/5414157.html
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/116432.html
