Reputation: 960
I have a text file with hexadecimal values, after I fscanf a value I need to know how I can convert it from hexadecimal string to an int. And then convert it back to hexadecimal string for a later print. Anyone knows an algorithm for this? thank you.
Upvotes: 0
Views: 2609
Reputation: 6775
As Marlon said above:
int a, b, c;
fscanf(fp, "%x %x %x", &a, &b, &c);
To print back as hex strings
fprintf(fp, "%x %x %x", a, b, c);
I think that you might be confused about the way the computer stores variables of type int
. They are not stored in base 10. They are stored in binary, as I'm sure you know. That means that there is nothing special about assigning a hex value to an int
. It won't be stored any differently. Using the %x
just shows that you want the program to understand that the number you are giving it is a hex number (for example so it knows to store the string "10" as 10000(2) rather than as 1010(2). Same thing with output. If your variable a
has the binary 10000(2) and you print it using %x
, the program knows that the output should be 10
. If you use %d
, it knows that the output should be 16
.
Upvotes: 2
Reputation: 20332
You should use the %x
format specifier instead of %s
to read your values. This will read the data as hexadecimal integers.
For example, if your file looks like this:
ff3c 5a cb2d
Then you can read those 3 values like this:
int a, b, c;
fscanf(fp, "%x %x %x", &a, &b, &c); // a = 0xff3c, b = 0x5a, c = 0xcb2d
Upvotes: 4
Reputation: 272812
Use the %x
format specifier in your fscanf
and fprintf
strings.
Upvotes: 3