/*********************************************************************************************************
文件名称 : 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");
}