php中的ip2long和long2ip的理解
2024-08-23 21:31:43
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
最新文章
- 第二天ci项目规划 前后台分离
- linux kernel链表
- iOS 9正式版开始推送 升级机型非常广泛
- POJ 3678 Katu Puzzle(强连通 法)
- hibernate多对多映射关系实现
- C++: getline函数
- java基础 (java工程师入门应该了解的)
- LINUX下的时间与时区的设置
- ios 阻止GDB依附
- html.ex.day01
- python文件_目录
- poj2187(未完、有错)
- Keras官方中文文档:Keras安装和配置指南(Windows)
- Spring ioc 详解
- EnableEurekaServer基本配置
- 关闭VS警告 warning C4996
- Python比较(关系)运算符
- eclipse 设置
- shell脚本编写informix数据库中表的导入和导出
- OpenGL中移动单位中的‘单位’指什么