在int中存储十六进制数

时间:2015-01-05 22:12:03

标签: c loader systems-programming

尝试使用以下输入实现绝对加载器: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]!='\0';length++);

for (i = 0;hex[i]!='\0'; ++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;
}

不确定如何开始&#39;存储&#39;地址&#39; ...目前的价值。&#39;开始&#39;打印1000H ...请帮助我存储十六进制值&#39;地址&#39;在上面的实现中,int&#39; start&#39; ...输入和输出文件已附上... thx!

1 个答案:

答案 0 :(得分:2)

如果十六进制数字存储在字符串hex中,其格式为0x...0X......,其中点代表 {{1}中的数字} base 然后您可以使用16函数将值存储在 {{1中的整数sscanf()(下例)中)基地

decimalNumber

这是一个完整的例子

10

输出将是

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