PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Fri Jun 20, 2008 9:24 pm |
|
|
Quote: | I would like to capture a string of hex then store it into the EEPROM... |
I assume you mean ASCII hex characters. The following routine
converts up to 2 digits of ASCII hex chars to an 8-bit unsigned int.
You can use strlen() to get the length of the string in your buffer.
Then use a for() loop to convert two digits per pass.
Code: |
// Convert a string of 1 or 2 ascii hex characters to a binary value.
int8 axtoi(char *ptr)
{
int8 i, temp, value;
value = 0;
for(i = 0; i < 2; i++) // Convert a maximum of 2 digits
{
temp = toupper(*ptr++); // Get the char. Convert to upper case
if(isxdigit(temp) == FALSE) // Is ascii char a hex digit ?
break; // Break if not
temp -= 0x30; // Convert the char to binary
if(temp > 9)
temp -= 7;
value <<= 4; // shift existing value left 1 nybble
value |= temp; // Then combine it with new nybble
}
return(value);
} |
Example:
Code: | void main()
{
char array[20] = {"0123456789ABCDEF"};
int8 len;
char *ptr;
int8 i;
len = strlen(array);
ptr = array;
for(i = 0; i < (len + 1)/2; i++)
{
printf("%x \n\r", axtoi(ptr));
ptr += 2;
}
while(1);
} |
|
|