C IP 大整数和字符串相互转换
程序员文章站
2022-04-12 16:28:11
...
原理很简单,大整数转字符串就是一直对256取余,取整
字符串转大整数就是一直乘256
#include <stdio.h>
#include <string.h>
void swapStr(char *str, int left, int right) {
int temp;
for (; left <= right; left++, right--) {
temp = str[left];
str[left] = str[right];
str[right] = temp;
}
}
void iptostr(unsigned int ipint) { //大整数IP转字符串IP
char ipstr[15] = {0};
// printf("[ipstr] : %s\n", ipstr);
char temp[4];
int begin, end, len, cur;
while (ipint) {
// puts("------------------");
cur = ipint % 256;
sprintf(temp, "%d", cur);
// printf("[temp] : %s\n", temp);
strcat(ipstr, temp);
// printf("[ipstr] : %s\n", ipstr);
ipint /= 256;
// printf("[ipint] : %d\n", ipint);
if (ipint) {
strcat(ipstr, ".");
// printf("[ipstr] : %s\n", ipstr);
}
}
len = strlen(ipstr);
swapStr(ipstr, 0, len - 1);
for (begin = 0, end = 0; end < len; end++, begin = end) {
while (end < len && ipstr[end] != '.')
end++;
swapStr(ipstr, begin, end - 1);
}
puts(ipstr);
return;
}
uint ipTint(char *ipstr) //字符串转整形
{
if (ipstr == NULL)
return 0;
char *temp = NULL;
uint i = 3, total = 0, cur;
temp = strtok(ipstr, ".");
while (temp != NULL) {
cur = atoi(temp);
if (cur >= 0 && cur <= 255) {
total += cur * pow(256, i);
}
i--;
temp = strtok(NULL, ".");
}
return total;
}
int main(void) {
unsigned int ipint;
scanf("%d", &ipint);
iptostr(ipint);
}