前言
最近看道一个面试题目,大体意思就是将ip地址,例如“192.168.1.116”转换成int类型,同时还能在转换回去
思路
ip地址转int类型,例如ip为“192.168.1.116”,相当于“.“将ip地址分为了4部分,各部分对应的权值为256^3, 256^2, 256, 1,相成即可
int类型转ip地址,思路类似,除以权值即可,但是有部分字符串的操作
实现代码
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define LEN 16
typedef unsigned int uint;
/**
* 字符串转整形
*/
uint ipTint(char *ipstr)
{
if (ipstr == NULL) return 0;
char *token;
uint i = 3, total = 0, cur;
token = strtok(ipstr, ".");
while (token != NULL) {
cur = atoi(token);
if (cur >= 0 && cur <= 255) {
total += cur * pow(256, i);
}
i --;
token = strtok(NULL, ".");
}
return total;
}
/**
* 逆置字符串
*/
void swapStr(char *str, int begin, int end)
{
int i, j;
for (i = begin, j = end; i <= j; i ++, j --) {
if (str[i] != str[j]) {
str[i] = str[i] ^ str[j];
str[j] = str[i] ^ str[j];
str[i] = str[i] ^ str[j];
}
}
}
/**
* 整形转ip字符串
*/
char* ipTstr(uint ipint)
{
char *new = (char *)malloc(LEN);
memset(new, '\\0', LEN);
new[0] = '.';
char token[4];
int bt, ed, len, cur;
while (ipint) {
cur = ipint % 256;
sprintf(token, "%d", cur);
strcat(new, token);
ipint /= 256;
if (ipint) strcat(new, ".");
}
len = strlen(new);
swapStr(new, 0, len - 1);
for (bt = ed = 0; ed < len;) {
while (ed < len && new[ed] != '.') {
ed ++;
}
swapStr(new, bt, ed - 1);
ed += 1;
bt = ed;
}
new[len - 1] = '\\0';
return new;
}
int main(void)
{
char ipstr[LEN], *new;
uint ipint;
while (scanf("%s", ipstr) != EOF) {
ipint = ipTint(ipstr);
printf("%u\\n", ipint);
new = ipTstr(ipint);
printf("%s\\n", new);
}
return 0;
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关文章
猜你喜欢
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 53
-
2025-05-29 100
-
2025-05-27 83
-
2025-05-26 22
-
在CentOS7系统上编译安装MySQL 5.7.13步骤详解
2025-05-25 96
热门评论

