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\n", ret); char str[512];
long2ip(ret, str, sizeof(str));
printf("long2ip=%s\n", str);
}

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

最新文章

  1. 第二天ci项目规划 前后台分离
  2. linux kernel链表
  3. iOS 9正式版开始推送 升级机型非常广泛
  4. POJ 3678 Katu Puzzle(强连通 法)
  5. hibernate多对多映射关系实现
  6. C++: getline函数
  7. java基础 (java工程师入门应该了解的)
  8. LINUX下的时间与时区的设置
  9. ios 阻止GDB依附
  10. html.ex.day01
  11. python文件_目录
  12. poj2187(未完、有错)
  13. Keras官方中文文档:Keras安装和配置指南(Windows)
  14. Spring ioc 详解
  15. EnableEurekaServer基本配置
  16. 关闭VS警告 warning C4996
  17. Python比较(关系)运算符
  18. eclipse 设置
  19. shell脚本编写informix数据库中表的导入和导出
  20. OpenGL中移动单位中的‘单位’指什么

热门文章

  1. Android判断屏幕开关状态
  2. iOS开发--Swift 如何完成工程中Swift和OC的混编桥接(Cocoapods同样适用)
  3. 苹果企业账号打包发布APP流程详解
  4. NSPredicate
  5. ArrayList vs LinkedList vs Vector
  6. 如何分析解读systemstat dump产生的trc文件
  7. .NET领域驱动设计—实践(穿过迷雾走向光明)
  8. Sql Server 添加外部程序集基本操作
  9. Python基础之装饰器
  10. 烂泥:高负载均衡学习haproxy之TCP应用