General programs operate on strings, but serial programs often use hexadecimal strings. In my community, I saw a great hero's conversion algorithm, which I posted and contributed.
Char converthexchar (char ch );
Int string2hex (cstring STR, cbytearray & senddata, char * tag );
Function: converts a string of the cstring type to the cbytearray type and stores it in senddata. The tag is a separator.
Function prototype:
Int string2hex (cstring STR, cbytearray & senddata, char * tag)
{
Int hexdata, lowhexdata;
Int hexdatalen = 0;
Int Len = Str. getlength ();
Senddata. setsize (LEN/2 );
For (INT I = 0; I <Len ;)
{
Char lstr, hstr = STR [I];
If (! Strcmp (hstr, tag)
{
I ++;
Continue;
}
I ++;
If (I> = Len)
Break;
Lstr = STR [I];
Hexdata = converthexchar (hstr );
Lowhexdata = converthexchar (lstr );
If (hexdata = 16) | (lowhexdata = 16 ))
Break;
Else
Hexdata = hexdata * 16 + lowhexdata;
I ++;
Senddata [hexdatalen] = (char) hexdata;
Hexdatalen ++;
}
Senddata. setsize (hexdatalen );
Return hexdatalen;
}
Char converthexchar (char ch)
{
If (CH> = '0') & (CH <= '9 '))
Return ch-0x30;
Else if (CH> = 'A') & (CH <= 'F '))
Return ch-'A' + 10;
Else if (CH> = 'A') & (CH <= 'F '))
Return ch-'A' + 10;
Else return (-1 );
}
Example:
The hexadecimal data to be sent is: FF, 00, 00, 00, 3f, 00, # The Delimiter is ","
Cbytearray senddata;
Cstring STR = "ff, 00,00, 00, 3f, 00 ,##";
String2hex (STR, senddata ,",");
Next, we can send the data obtained by senddata. getdata () through the serial port, and then send the hexadecimal data.