闲来无事,写程序打发时间,典型的“白天瞎jb忙,晚上jb瞎忙”

/*********************************************************************************************************
文件名称 : conpe14.c
建立时间 : 2006-2-9 19:35
版权所有 : 东软股份大连分公司电信事业开发部
Author   : 中介部.吴喆喆
文件描述 : 
修改记录 :
========================================================================================================
序号 修改日期    修改人 修改原因
1. 统一用指针p, 不用tmp了, 否则麻烦. 因为strcat返回的是char *, 不能给tmp直接赋值, 所以就麻烦了
2. %x改为%X, 不用自己写小写转大写的了
3. %X改为%02X, 不用自己另外加0了, 如果是一个0的话
4. 更好的方法还是看人家高手写的吧, c/other_people/DecToHex.c
*********************************************************************************************************/

#include <stdlib.h>
#include <string.h>

char cstr[20];  /*也可以不用全局变量的, 在Dec的最后作为开始, 存储转换后的串, 然后返回这个位置*/
char cstr2[20];

char *DecToHex(char *Dec)
{
 /*eg: Dec是30.10.191.194*/
 char *token;
 //char tmp[5];   /*不用tmp了, 否则麻烦. 因为strcat返回的是char *, 不能给tmp直接赋值, 所以就麻烦了*/
 char *p;
 int count = 0;
 
 p = (char *)malloc(5);
 memset(cstr, 0, 20);

 for (token = strtok(Dec, "."); token != NULL; token = strtok(NULL, "."))
 {
  sprintf(p, "%02X", atoi(token));  /*转成十六进制然后赋给p, X表示转成大写字母*/

  memcpy(cstr+count, p, strlen(p));
  count += strlen(p);
 }
 
 return cstr;
}

char *HexToDec(char *Hex)
{
 /*eg: Hex是1E0ABFC2*/
 int tmp;
 int count = 0;
 char stmp[5];
 memset(cstr2, 0, 20);
 
 while (*Hex != '/0')
 {
  if (isdigit(*Hex))
   tmp = (*Hex-'0') * 16;
  else
   tmp = (*Hex-'A'+10) * 16;
  
  ++Hex;   /*因为是1E0ABFC2这种格式, 所以没有必要判断++Hex是否为NULL*/
  if (isdigit(*Hex))
   tmp += (*Hex-'0');
  else
   tmp += (*Hex-'A'+10);
  
  sprintf(stmp, "%d", tmp);
  
  memcpy(cstr2+count, stmp, strlen(stmp));
  count += strlen(stmp);
  memcpy(cstr2+count, ".", 1);
  ++count;
  ++Hex;
 }
 cstr2[--count] = '/0';  /*去掉最后的"."号*/
 printf("%s/n", cstr2);
}


int main(void)
{
 char des[] = "30.10.191.194";
 char *temp;
 temp = DecToHex(des);
 printf("%s/n", temp);
 
 
 //HexToDec("1E0ABFC2");
 
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值