#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!=' ') {
//用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
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.163n",argv[0]);
exit(0);
}
//注意hex可能是4位或者是6位,动态变化
char *hex=argv[1];
//初始位数为1
int bit_length = 1;
while(*hex!=' ') {
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!=' ') {
if(*old++=='.') {
s[count]=' ';
value[index++] = str2int(s);
s=old;
count = 0;
}
else
count++;
if(*(old+1)==' ')
value[index++] = str2int(s);
}
//输出转换结果
printf("0x%sn",int_to_string_of_base_16(value,bit_length));
exit(0);
}