Issue
I have a text file in C containing hex values in this format:
F4 C3 56 78 A3
I want to store the decimal equivalents of these hex numbers into an unsigned char* array.
I know how to load the hex values into the array, but not how to convert them to decimal.
How can I do this?
Thanks
Solution
A mix with sscanf et prinf can do the job.
#include <stdio.h>
bool isHexaDigit(char p) {
return (( '0' <= p && p <= '9' ) || ( 'A' <= p && p <= 'F'));
}
int main(int argc, char** argv)
{
char t[]="F4 C3 FF 00 78 A3";
char* p = t;
char val[3]; // 2 hexa digit
val[2] = 0; //and the final \0 for a string
int number;
while (isHexaDigit(*p) && isHexaDigit(*(p+1))) {
val[0] = *p;
val[1] = *(p+1);
sscanf(val,"%X", &number); // <---- Read hexa string into number
printf("\nNum=%i",number); // <---- Display number to decimal.
p++;
p++;
if (!*p) break;
p++;
}
return 0;
}
Answered By - Florent Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.