1.代码
-
#include "utils.h"
-
-
long long htoi(const char* s, int len)
-
{
-
int i;
-
long long n = 0;
-
//现在保证s中是合法的并且都是小写的16进制字符串了,直接转就可以了
-
for (i=0; i<len; i++)
-
{
-
if (s[i] > '9')
-
{
-
n = 16*n + (10+ s[i]-'a');
-
}
-
else
-
{
-
n = 16*n + s[i]-'0';
-
}
-
}
-
return n;
-
}
-
-
int check_and_tran(char *d, char* s, int len)
-
{
-
int i;
-
//把去掉字符串开头的0x或0X,拷贝到d中
-
if (s[0] == '0' && (s[1]=='x' || s[1]=='X')) //0x or 0X, prefix
-
i=2;
-
else
-
i=0;
-
strncpy(d, s+i, len-i);
-
//printf("before d=%s\n", d);
-
-
//判断d中是不是合法字符,并把其中的大写字母转小写
-
for(i=0; i<strlen(d); i++)
-
{
-
// printf("%d=%c ", i, d[i]);
-
if( !((d[i]>='0' && d[i]<='9') || (d[i]>='a' && d[i]<='f') || (d[i]>='A' && d[i]<='F')) )
-
{
-
printf("not a valid hex string\n");
-
return -1;
-
}
-
if(d[i]>='A' && d[i]<='F')
-
d[i] += 'a' - 'A';
-
}
-
//printf("d=%s\n", d);
-
return 0;
-
}
-
-
int main ( int argc, char *argv[] )
-
{
-
int ret;
-
char buf[1024];
-
int len;
-
long long num;
-
if(argc < 2)
-
{
-
printf("./cal \n");
-
return -1;
-
}
-
memset(buf, 0 , 1024);
-
//1. 先检查传入的字符串是否是合法的16进制字符串
-
//把字符串中的A-F转为a-f,转为小写字母
-
ret = check_and_tran(buf, argv[1], strlen(argv[1]));
-
if(ret < 0)
-
return -1;
-
-
//2. 将16进制字符串转为10进制的数
-
num = htoi(buf, strlen(buf));
-
-
//3.最后按照合适的顺序打印出来
-
printf("0x%s=%lld\t", buf,num);
-
if(num > 1024)
-
printf("%lfK\t",(double)((double)num/1024));
-
if(num > 1024*1024)
-
printf("%lfM\t",(double)((double)num/1024/1024));
-
if(num > 1024*1024*1024)
-
printf("%lfG\t",(double)((double)num/1024/1024/1024));
-
printf("\n\n");
-
return EXIT_SUCCESS;
-
}
2. 代码打包
calculator.rar(下载后改改为calculator.tar.gz)
3. 实验结果
-
cong@msi:/work/test/calculator$ ./cal E4B00010
-
e4b00010=3836739600 3746816.015625K 3659.000015M 3.573242G
-
-
cong@msi:/work/test/calculator$ ./cal 1234
-
1234=4660 4.550781K
阅读(2304) | 评论(0) | 转发(0) |