I am trying to find a better way to convert a string of 4 Hex character to integer so that I can do the compare and do necessary action.
I am using a wireless communication to get ADC value from sensors and the return was string character of the value in Hex.
e.g. from 0000 to 2EEE.
I saw the atoi function in Keil C but it can only convert 0-9 and not A to F. Is there any function that can convert this 2 bytes data into integer?
Currently my method of conversion was quite lengthy. I will use a lookup table and convert all the string Hex into binary
e.g. 'F' (0x46) --> 0x0F, merge the individual 4 bit into a byte, then merge the 2 byte into an integer. Then only I can process the integer.
Hi bigdog, can I ask about the function u write, I will received the Hex string in a data buffer, let's say the 4 hex to convert into int is in data[x-4], data[x-3], data[x-2] and data[x-1]. How can I write my function in the main so that I can get the return integer?
Is it like this
Code:
unsigned int ADCvalue;
ADCvalue = ahtoi(data[x-4], data[x-3], data[x-2] and data[x-1]);
The very good solution proposed by BigDog requires a null terminated string. So just add a 0x00 after the last hex digit and call the function with the pointer to the first hex digit.
If however the sscanf() adds a long code, you can try using a 'homemade' conversion look like:
Code:
unsigned short hex_to_short(unsigned char* buffer)
{
unsigned char k,i;
unsigned short n;
for(i=0;i<4;i++)
{
k=*(buffer+i)-48;
if (k>9) //hex digit not a number
k-=7;
k&=0x0f; //lowercase or wrong hex digit
n=(n<<4) | k;
}
return n;
}
I try using data buffer to individually called your function. But it still give me illegal pointer conversion. Sorry, really not so good at pointer. Can advise?
Great thanks to you. You code is simple to understand for novice like me. I had try it and it works for my application and I understand the concept behind your program. This is my test program and I can convert the string "2EEE" into unsigned int 2EEE. Thanks again
Code:
unsigned int Stringhex_to_hex(unsigned char* buffer)
{
unsigned char k,i;
unsigned int n;
for(i=0;i<4;i++)
{
k=*(buffer+i)-48;
if (k>9) //hex digit not a number
k-=7;
k&=0x0f; //lowercase or wrong hex digit
n=(n<<4) | k;
}
return n;
}
void main (void)
{
unsigned int ADCvalue;
unsigned char Data[4];
Data[0] = '2';
Data[1] = 'E';
Data[2] = 'E';
Data[3] = 'E';
ADCvalue = Stringhex_to_hex(&Data[0]);
}