Convert string to hexadecimal

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.