加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C/C++ ip地址与int类型的转换实例详解

发布时间:2020-12-16 05:15:11 所属栏目:百科 来源:网络整理
导读:C/C++ ip地址与int类型的转换实例详解 前言 最近看道一个面试题目,大体意思就是将ip地址,例如“192.168.1.116”转换成int类型,同时还能在转换回去 思路 ip地址转int类型,例如ip为“192.168.1.116”,相当于“.“将ip地址分为了4部分,各部分对应的权值为2

C/C++ ip地址与int类型的转换实例详解

前言

最近看道一个面试题目,大体意思就是将ip地址,例如“192.168.1.116”转换成int类型,同时还能在转换回去

思路

ip地址转int类型,例如ip为“192.168.1.116”,相当于“.“将ip地址分为了4部分,各部分对应的权值为256^3,256^2,256,1,相成即可

int类型转ip地址,思路类似,除以权值即可,但是有部分字符串的操作

实现代码

#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,'',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,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] = ''; 
 
  return new; 
} 
 
int main(void) 
{ 
  char ipstr[LEN],*new; 
  uint ipint; 
 
  while (scanf("%s",ipstr) != EOF) { 
    ipint = ipTint(ipstr); 
    printf("%un",ipint); 
 
    new = ipTstr(ipint); 
    printf("%sn",new); 
  } 
 
  return 0; 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读