tags:

views:

100

answers:

3

Hey, I got a file full with hexadecimal addresses, I've managed to parse the file and fetch them yet I must convert them back to unsigned long, what's the best algorithm or fast way to do so considering the file is very long (a few megs) ?

Thanks in advance.

A: 

a few meg is not big ! You should do this with a script language, e.g. in python

out = open("outfile", "w")
try:
    for line in open(myfile, "r"):
        out.write(int(line, 16))
finally:
    out.close()

Assuming it is one hex/line. Even if your hex are not consistent, and you need a regex to parse them, it will almost certainly take less than a few seconds on a decent computer. I would not bother with C unless you file is several GB :)

Now, if you need to do this in C, writing the integers is very easy once you have parsed them. What's your problem exactly ? To write to a file ? Or you do have the hex numbers as strings in a file ? In that later case, you could use fscanf with the x format. Or str* functions, as suggested by Jared.

David Cournapeau
Did you take two of everything in your medicine cabinet and realize that you could fly, then attribute this super power to Python?Good, me too.
Tim Post
I said python like I could have said any other scripting language. The point was that using C for this is not really appropriate, unless he needs to do it within a bigger program (itself in C).
David Cournapeau
+5  A: 

You can start with strtoul. It's part of the standard C library, but I include a link here from the C++ reference.

char buffer[5];
unsigned long val;
... /* read another 4 valid characters from the file into buffer */
buffer[4] = '\0';
val = strtoul(buffer, NULL, 16);
...
Jared Oberhaus
Be sure to catch the errno from strto*, they were implemented _for_ error checking (as opposed to ato*())
Tim Post
Actually I'm looking for a bit-juggling solution,is it even attainable ? possible ? If so - any hints for the algo ?Thanks in advance.
A: 

If you already have your input parsed then you might as well just use:

unsigned long num;
sscanf(your_hex_string, "%lx", &num);
jtb