我读取到的的16进制数 0, 0, 6b6, 6a5, 695, 685, 67e, 663, 662, 652, 648, 640, 62e, 628, 616, 612, 604, 5f7, 5ed, 5df,是这样的600个数据,我写的代码如下,可为什么转化的是错的,请大神们帮忙看一下。
#include
#include
#include
#include
#include
#define N 600
int main()
{
char szTest[1000] = {0};
int len = 0;
FILE *fp = fopen("data25.txt", "r");
if(NULL == fp)
{
printf("failed to open dos.txt\n");
return 1;
}
while(!feof(fp))
{
memset(szTest, 0, sizeof(szTest));
fgets(szTest, sizeof(szTest) - 1, fp); // 包含了\n
int t=strlen(szTest);
long sum=0;
for(int i=0;i<t;i++){
if(szTest[i]>='a' && szTest[i]<='z')
szTest[i]=int(szTest[i]-'a')+10+'0';
sum+=((szTest[i]-'0')*(pow(16,t-1-i)));
sum1[]=sum;
}
printf("%ld\n",sum);
}
fclose(fp);
printf("\n");
return 0;
}
/*unsigned convert(char szTest[]) {
unsigned i,num = 0;
for(i = 0;szTest[i];++i) {
szTest[i] = toupper(szTest[i]); //* 小写字母转换成大写,其他字符不变 *
if(isalpha(szTest[i])) num += 16 * num + szTest[i] - 'A';
else num += 16 * num + szTest[i] - '0';
}
return num;
}
*/
你的程序看不大懂 ,改了一下,可以了。
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//#include
//#include
#define N 600
#ifndef BOOL
#define BOOL int
#define TRUE 1
#define FALSE 0
#endif
BOOL isHexNum(char c)
{
if((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))
return TRUE;
return FALSE;
}
int main()
{
char outArray[N][8]={0};
int outDec[N] = {0};
int len = 0;
int count = 0;
FILE *fp = fopen("d:\\test\\data25.txt", "r");
if(NULL == fp)
{
printf("failed to open dos.txt\n");
return 1;
}
int status = 0 ;
while(!feof(fp))
{
char c = fgetc(fp);
if(status==0)
{
if(isHexNum(c))
{
status = 1;
outArray[count][len] = c;
len+=1;
}
}
else if(status==1)
{
if(isHexNum(c))
{
outArray[count][len] = c;
++len;
}
else
{
++count;
status = 0;
len = 0;
}
}
}
fclose(fp);
for(int i=0;i<count;i++)
{
sscanf(outArray[i],"%x",&outDec[i]);
printf("%d\n",outDec[i]);
}
printf("\n");
return 0;
}
输入:
0, 0, 6b6, 6a5, 695, 685, 67e, 663, 662, 652, 648, 640, 62e, 628, 616, 612, 604, 5f7, 5ed, 5df,
输出:
0
0
1718
1701
1685
1669
1662
1635
1634
1618
1608
1600
1582
1576
1558
1554
1540
1527
1517
1503
这个转换要看你怎么转,因为有不同的编码和字节序,结果是不同的,最好你有一个参照的结果,然后再写。