在 int 中存储十六进制数

Storing a hexadecimal number in an int

尝试使用来自的输入实现绝对加载器:http://pastebin.com/k7VkA3xQ

当前获得的输出:http://pastebin.com/FiYPMWrZ

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <string.h>


int dec(char hex[]){ //function converts a hex array of characters to its equivalent decimal value

int length,i,sum=0;
for(length=0;hex[length]!='[=10=]';length++);

for (i = 0;hex[i]!='[=10=]'; ++i,--length)
{
    if (hex[i]>='0' && hex[i]<='9') 
        sum+=(hex[i]-'0')*pow(16,length-1);
    else if (hex[i]>='A' && hex[i]<='Z')    
        sum+=hex[i]-'A'+10;
    else if (hex[i]>='a' && hex[i]<='z')    
        sum+=hex[i]-'a'+10;
}
return sum;
}


int main(int argc, char const *argv[])
{
char record[2],progname[10],startaddr[10],proglen[10],addr[10],len[10];
int start,address,diff,flag=1,decimal;
FILE *fptr;

if (access("Input.dat",F_OK)!=-1)
{
    fptr = fopen("Input.dat","r");
    printf("File opened successfully\n");
}
else
{
    printf("File opened unsuccessfully\n");
    exit(1);
}


fscanf(fptr,"%s",record);
if (strcmp(record,"H")==0){
    fscanf(fptr,"%s",progname);fscanf(fptr,"%s",startaddr);fscanf(fptr,"%s",proglen);
}

fscanf(fptr,"%s",record);
while(strcmp(record,"T") == 0 ){
    fscanf(fptr,"%s",addr);fscanf(fptr,"%s",len);
    if (flag)
        sscanf(startaddr,"%x",&start);
    else
        start = address; //'start' fails to store the hex value of 'address'

    sscanf(addr,"%x",&address);
    diff = address - start;
        while((diff--)>0){
            printf("%x              xx\n",start++);
    }
    decimal = dec(len)%3==0?dec(len)/3:dec(len)/3+dec(len)%3;
    while(decimal--){
        fscanf(fptr,"%s",addr);
        printf("%x              ",address++);   printf("%c%c\n",addr[0],addr[1]);   
        printf("%x              ",address++);   printf("%c%c\n",addr[2],addr[3]);   
        printf("%x              ",address++);   printf("%c%c\n",addr[4],addr[5]);   
    }
        fscanf(fptr,"%s",record);
}


return 0;
}

不确定如何让'start'存储'address'的值...目前..'start'从1000H打印...请帮助我存储十六进制int 'start' 中的值 'address'...上面已附上上述实现的输入和输出文件...谢谢!

如果十六进制数以 0x...0X...... 形式存储在字符串 hex 中,其中点代表 中的数字16 base 然后您可以使用 sscanf() 函数将值存储在 整数 中(decimalNumber 用于下面的示例) 在10基础

sscanf(hex,"%x",&decimalNumber);

所以对于一个完整的例子

char hex[100]="0xf";
int decimalNumber;
sscanf(hex,"%x",&decimalNumber);
printf("The value of decimalNumber is %d\n",decimalNumber);

输出将是

The value of decimalNumber is 15