首页 > 其他 > 详细

点分十进制形式的ip地址转化为十六进制数

时间:2015-07-02 12:27:02      阅读:266      评论:0      收藏:0      [点我收藏+]
#include "csapp.h"
/*本代码将点分十进制形式的ip地址转化为十六进制数并且输出*/

//返回一个字符串代表的整数
int str2int(char *str)
{
  //要注意变量的初始化
  int value=0;
  //字符串长度
  int length = strlen(str);
  //基数
  int base=1;
  while(--length!=0) {
    base*=10;
  }
  while(*str!=‘\0‘) {
    //用ascii码来计算
    int c = *str++;
    value = value + (c - 48) * base;
    base/=10;
  }
  return value;
}

//将十进制整数转化为16进制整数并以字符形式输出
char base_10_to_base_16(int value)
{
  if(value>=0&&value<=9)
    return (value+48);
  else if(value>=10&&value<=15)
    return (value-10+97);
}

//将16进制整数数组转化为字符串输出,调用上面的base_10_to_base_16函数
char* int_to_string_of_base_16(int value[],int bit)
{
  char* str = (char *)malloc(sizeof(char)*2*bit);
  char* copy_str = str;
  int i;
  for(i=0;i<bit;i++) {
    int bit_1 = value[i]/16;
    int bit_2 = value[i]%16;
    *str++ = base_10_to_base_16(bit_1);
    *str++ = base_10_to_base_16(bit_2);
  }
  return copy_str;
}

//主函数
void main(int argc,char* argv[])
{
  if(argc<2) {
    printf("input error!you should input like this:%s 172.20.4.163\n",argv[0]);
    exit(0);
  }
  //注意hex可能是4位或者是6位,动态变化
  char *hex=argv[1];
  
  //初始位数为1
  int bit_length = 1;
  while(*hex!=‘\0‘) {
    if(*hex++==‘.‘)
      bit_length++;
  }
  int value[bit_length];

  //计数器
  int count = 0;
  int index = 0;
  char *s = argv[1];
  char *old = argv[1];
  char ch;
  while(*old!=‘\0‘) {
    if(*old++==‘.‘) {
      s[count]=‘\0‘;
      value[index++] = str2int(s);
      s=old;
      count = 0;
    }
    else
      count++;
    if(*(old+1)==‘\0‘)
      value[index++] = str2int(s); 
  }
  //输出转换结果
  printf("0x%s\n",int_to_string_of_base_16(value,bit_length));
  exit(0);
}


点分十进制形式的ip地址转化为十六进制数

原文:http://my.oschina.net/zzw922cn/blog/473208

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!