Cstring to a hexadecimal string

Source: Internet
Author: User

I recently encountered this problem when I was working on the project. For example, after converting the Chinese character "Chong" into "51b2 ",ProgramThe Unicode character set is used. The solution is as follows:

//---------------------------------------------------------------------
// Function: W2C
// Function: Convert 16-bit wchar_t to 8-bit char [2]
// Parameter: w_cn is the 16-bit character to be converted, and c_cn [] is the 8-bit character after conversion.
// Note: the high byte of wchar_t should be stored in the low byte of the char array
// Author: chuchong

//---------------------------------------------------------------------
Void styleconvert: W2C (wchar_t w_cn, char c_cn [])
{
// Following code convert wchar to Char
C_cn [0] = w_cn> 8;
C_cn [1] = (char) w_cn;
}
//-------------------------------------------------------------------
// Function: convertwchartohex
// Function: convert a 16-bit string to a hexadecimal string
// Parameter: string to be converted, String Length
// Return value: converted string
// Author: chuchong
//-------------------------------------------------------------------
Cstring styleconvert: convertwchartohex (cstring data, long ndatalength)
{
Cstring sresult ("");
For (long nloop = 0; nloop <ndatalength; nloop ++)
{
Wchar_t CH = data. getat (nloop );
// Convert wchar_t to Char [2]
Char c_cn [2] = {'0 '};
W2C (CH, c_cn );

Static const char * hex = "0123456789 abcdef ";
For (INT I = 0; I <2; I ++)
{
Unsigned char chhexa = hex [(unsigned char) (c_cn [I])> 4) & 0x0f];
Unsigned char chhexb = hex [(unsigned char) (c_cn [I]) & 0x0f];
Sresult + = (char) chhexa;
Sresult + = (char) chhexb;
}
}
Return sresult;
}

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.