原理很简单,大整数转字符串就是一直对256取余,取整
字符串转大整数就是一直乘256
#include <stdio.h>
#include <stdlib.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;
}
}
char ipstr[15] = {0};
void iptostr(unsigned int ipint) { //大整数IP转字符串IP
char temp[4];
int begin, end, len, cur;
while (ipint) {
cur = ipint % 256;
sprintf(temp, "%d", cur);
strcat(ipstr, temp);
ipint /= 256;
if (ipint) {
strcat(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);
}
unsigned int ipTint() //字符串转整形
{
long long int ip = 0;
int i = 4, j = 0, k;
unsigned int temp1, temp2;
while (i) {
temp1 = 1;
temp2 = 0;
while (ipstr[j] != '.' && j < strlen(ipstr)) {
temp2 = temp2 * 10 + (ipstr[j] - '0');
j++;
}
j++;
for (k = i - 1; k > 0; k--) {
temp1 *= 256;
}
ip += temp1 * temp2;
i--;
}
return ip;
}
int main(void) {
unsigned int ipint;
scanf("%d", &ipint);
iptostr(ipint);
printf("%u\n", ipTint());
}