Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

c - Converting HEX data in a file to ascii

i want to decode an ASN.1 standard binary file. i have converted the binary file to hex and stored it in a file. now i want to convert this hex to ascii. The problem im having now is how to read the hex file.

the file looks this way, 81 01 32 82 0D 35 31 34 32 34 31 38 38 38 where 81 is a header, 01 is the size and 32 is the data. again 82 is the header and this goes on. how do i read from this file and differentiate between the various fields present.

i searched all over the internet for this, but couldnt get a satisfactory answer. so can someone help me with the way forward . i dont want any code, just want the procedure how i can do it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would first read the header and then in a loop the data. You can read hexadecimal numbers with the "x"-specifier (say your file is named hexfile.txt):

#include <stdio.h>

int main ()
{

    FILE *stream;
    unsigned int h, l, d;

    if( (stream  = fopen( "hexfile.txt", "r" )) == NULL ) return 1;

    while (EOF != fscanf (stream, " %x %x", &h, &l))
    {
        printf ("%02X %02X
",h,l);

        for (unsigned i=0; i<l; ++i)
        {
            if (EOF == fscanf (stream, " %x", &d)) break;
            printf ("%02X ",d);
        }
        puts ("");
    }

    fclose (stream);

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...