Wchar_t, Char, String, cstring, BSTR, ccombstr, _ bstr_t, variant, _ variant_t and colevariant convert each other

Source: Internet
Author: User

Unicode (unified code, universal code, Single Code) is a character encoding used on a computer. It sets a unified and unique binary code for each character in each language to meet the requirements of cross-language and cross-platform text conversion and processing. R & D started in December 1990 and officially announced in December 1994. With the enhancement of computer capabilities, Unicode has been popularized in more than a decade since its launch. In a non-Unicode environment, because different countries and regions use different character sets, it is likely that all characters cannot be properly displayed. Microsoft uses the code page (codePage) conversion table technology to solve this problem in a transitional part, that is, the non-Unicode
To the Unicode encoding used in the system corresponding to the same character.

1. char * And wchar_t *

1. Convert single-byte char * to wide-byte wchar_t *

Wchar_t * cs2wcs (const char * sz)
{
Size_t Len = strlen (sz) + 1;
Size_t converted = 0;
Wchar_t * wsz = (wchar_t *) malloc (LEN * sizeof (wchar_t ));
Mbstowcs_s (& converted, wsz, Len, SZ, _ truncate );
Return wsz;
}

2. Convert the wide-byte wchar_t * to a single-byte char *
Char * wcs2cs (const wchar_t * wsz)
{
Size_t Len = wcslen (wsz) + 1;
Size_t converted = 0;
Char * SZ = (char *) malloc (LEN * sizeof (char ));
Wcstombs_s (& converted, SZ, Len, wsz, _ truncate );
Return SZ;

}

 

2. convert other data types to string
1. Short INTEGER (INT)
ITOA (I, temp, 10); // convert I to a string and put it into temp. the last digit indicates decimal.
ITOA (I, temp, 2); // convert in binary mode
2. Long Integer (long)
Ltoa (L, temp, 10 );
3. Floating Point Number (float, double)
Fcvt can be used to complete the conversion. This is an example in msdn:
Int decimal, sign;
Char * buffer;
Double Source = 3.1415926535;
Buffer = _ fcvt (source, 7, & decimal, & sign );
Running result: Source: 3.1415926535 Buffer: '20180101' decimal: 1 sign: 0
Decimal indicates the decimal point position, sign indicates the symbol: 0 is a positive number, and 1 is a negative number.
4. cstring variable
STR = "2008 Beijing Olympics ";
Non-Unicode
① Buf = (lpstr) (lpctstr) STR;
② String Buf (Str. getbuffer ());
Str. releasebuffer ();
Unicode
Convert it to char * first, and then assign a value directly.

5. BSTR variable
BSTR bstrvalue =: sysallocstring (L "programmer ");
Char * Buf = _ com_util: convertbstrtostring (bstrvalue );
Sysfreestring (bstrvalue );
Afxmessagebox (BUF );
Delete (BUF );
6. ccombstr variable
Ccombstr bstrvar ("test ");
Char * Buf = _ com_util: convertbstrtostring (bstrvar. m_str );
Afxmessagebox (BUF );
Delete (BUF );
7. _ bstr_t variable
_ Bstr_t is the encapsulation of BSTR. It is easy to use because = operator has been overloaded.
_ Bstr_t bstrvar ("test ");
Const char * Buf = bstrvar; // do not modify the Buf content
Afxmessagebox (BUF );

General method (for non-com data types)
Use sprintf to complete the conversion
Char buffer [200];
Char c = '1 ';
Int I = 35;
Long J = 1000;
Float F = 1.7320534f;
Sprintf (buffer, "% C", C );
Sprintf (buffer, "% d", I );
Sprintf (buffer, "% d", J );
Sprintf (buffer, "% F", F );

 

Iii. String Conversion to other data types
Temp = "123456 ";
1. Short INTEGER (INT)
I = atoi (temp );
2. Long Integer (long)
L = atol (temp );
3. Floating Point (double)
D = atof (temp );
String s; D = atof (S. c_str ());
4. BSTR variable
BSTR bstrvalue =: sysallocstring (L "programmer ");
... // Complete the use of bstrvalue
Sysfreestring (bstrvalue );
5. ccombstr variable
Ccombstr variables can be directly assigned values.
Ccombstr bstrvar1 ("test ");
Ccombstr bstrvar2 (temp );
6. _ bstr_t variable
_ Bstr_t type variables can be directly assigned values
_ Bstr_t bstrvar1 ("test ");
_ Bstr_t bstrvar2 (temp );

7. Convert string to char *

String is one of the C ++ standard libraries, which encapsulates string operations.
There are three methods to convert string to char:
(1) data
Stringstr = "ABC ";
Char * P = Str. Data ();
(2) c_str

String STR = "gdfd ";
   Char * P = Str. c_str ();
(3) Copy
String STR = "hello ";
Char P [40];
Str. Copy (p, 5, 0); // here, 5 represents the number of characters to be copied, and 0 represents the copy position.
* (P + 5) = '\ 0'; // You must manually add the Terminator.
Cout <P;

8. Convert string to wchar_t

# Include <stdlib. h>

String STR = "hello ";
Wchar_t * wsz;
Wsz = new wchar_t [Str. Size ()];
Mbstowcs (wsz, str. c_str (), str. Size ());

 

Iv. Conversion between cstring and other data types

1. convert other data types to cstring
Use the cstring member function Format for conversion. For example:
INTEGER (INT)         Str. Format ("% d", I );
Float)  Str. Format ("% F", I); doubledb = 777.999; Str. Format ("%. 8f", DB); Retain 8 decimal places
String pointer (char *) can be directly assigned STR = username;
For data types not supported by format, you can convert the data type to char * by using the method described above, and then assign the value to the cstring variable.
Note: Convert MFC smart device string to cstring
  String S = "123456 "; Cstring CSTR; CSTR = S. c_str ();

2. Convert cstring to double or float

(1) dB = atof (lpctstr) Str );

(2) Implementation through user-defined functions

Void cstringtofloat (cstring CSTR, double & F) // void cstringtofloat (cstring CSTR, float & F)
{
Int nlength = CSTR. getlength ();
Int nbytes = widechartomultibyte (cp_acp, 0, CSTR, nlength, null, 0, null, null );
Char * pcontentbuff = new char [nbytes + 1];
Memset (pcontentbuff, 0, nbytes + 1 );
Widechartomultibyte (cp_oemcp, 0, CSTR, nlength, pcontentbuff, nbytes, null, null );
Pcontentbuff [nbytes] = 0;
F = atof (pcontentbuff );
}

3. Convert cstring to int

How to convert a cstring to an int is described on the Internet by using the atoi function, but the cstring is internally stored as a wchar_t character, each character occupies two bytes, And the atoi parameter is char *, each character occupies one byte. If it is forcibly converted to char *, it is converted to a string with only the first character because the high byte is null. This is wrong. the _ wtoi function should be used. The parameter of this function is wchar_t *, for example:
Cstring STR ("123 ");
Int num = _ wtoi (STR );
Similarly, functions such as _ wtof () and _ wtol () can be used to convert cstring into different numerical types.

4. When the compiler uses a Unicode Character Set, the cstring type is converted to char * or char [].
(1)

Cstring origcstring ("Hello, world! ");
Wchar_t * wcharstring = origcstring. getbuffer (origcstring. getlength () + 1 );
Size_t origsize = wcslen (wcharstring) + 1;
Size_t convertedchars = 0;
Char * charstring;
Charstring = new char (origsize );
Wcstombs_s (& convertedchars, charstring, origsize, wcharstring, _ truncate );

(2)

Uses_conversion; // This macro is defined in atlbase. h.
Cstring testtext = _ T (""); // Note whether it is Unicode or ANSI.
Tchar * tcptr = testtext. getbuffer (); // Unicode returns wchar_t *, ANSI returns char *
Char * P = T2A (tcptr); // here you will get the final char * you want. It won't be garbled in Unicode or ANSI.

When Unicode is used

Uses_conversion; // This macro is defined in atlbase. h.
Cstring testtext = _ T (""); char * P = T2A (testtext );

(3)

Wstring multchartowidechar (string Str)
{
// Obtain the buffer size and apply for space. The buffer size is calculated by characters.
Int Len = multibytetowidechar (cp_acp, 0, str. c_str (), str. Size (), null, 0 );
Tchar * buffer = new tchar [Len + 1];
// Convert multi-byte encoding to wide-byte encoding
Multibytetowidechar (cp_acp, 0, str. c_str (), str. Size (), buffer, Len );
Buffer [Len] = '\ 0'; // Add the end of the string
// Delete the buffer and return the value
Wstring return_value;
Return_value.append (buffer );
Delete [] buffer;
Return return_value;
}
String widechartomultichar (wstring Str)
{
String return_value;
// Obtain the buffer size and apply for space. The buffer size is calculated in bytes.
Int Len = widechartomultibyte (cp_acp, 0, str. c_str (), str. Size (), null, 0, null, null );
Char * buffer = new char [Len + 1];
Widechartomultibyte (cp_acp, 0, str. c_str (), str. Size (), buffer, Len, null, null );
Buffer [Len] = '\ 0 ';
// Delete the buffer and return the value
Return_value.append (buffer );
Delete [] buffer;
Return return_value;
}
Therefore
String mstring = widechartomultichar (lpctstr) mcstring );
Strcpy_s (Pach, sizeof (Pach), mstring. c_str ());
Conversion successful!

 

 

V. BSTR, _ bstr_t and ccombstr
Ccombstr is the encapsulation of BSTR by ATL, _ bstr_t is the encapsulation of BSTR by C ++, and BSTR is a 32-bit pointer, but it does not directly point to the buffer of the string.
Char * can be converted to BSTR as follows:
Bstr B = _ com_util: convertstringtobstr ("data"); // comutil. h and comsupp. Lib must be added before use.
Sysfreestring (bstrvalue );
Otherwise, char * P = _ com_util: convertbstrtostring (B); Delete P;

Ccombstr and _ bstr_t overload a large number of operators. You can directly perform = ,! =, = And so on, so it is very convenient to use.

 

6. Variant, _ variant_t, and colevariant
For the Variant Structure, refer to the definition of the tagvariant struct in the header file vc98 \ include \ oaidl. h.
Assign a value to the variant variable: assign a value to the VT member to specify the data type, and then assign a value to the variable of the same data type in the union structure. For example:
Variant Va;
Int A = 2001;
Va. Vt = vt_i4; // specify Integer Data
Va. lval = A; // value assignment
For variant that is not immediately assigned a value, it is best to initialize with void variantinit (variantarg far * pvarg); in essence, the VT is set to vt_empty, the following table lists the correspondence between VT and common data:
Byte bval; // vt_ui1.
Short ival; // vt_i2.
Long lval; // vt_i4.
Float fltval; // vt_r4.
Double dblval; // vt_r8.
Variant_bool boolval; // vt_bool.
Scode; // vt_error.
Cy cyval; // vt_cy.
Date; // vt_date.
BSTR bstrval; // vt_bstr.
Decimal far * pdecval // vt_byref | vt_decimal.
Iunknown far * punkval; // vt_unknown.
Idispatch far * pdispval; // vt_dispatch.
Safearray far * parray; // vt_array | *.
Byte far * pbval; // vt_byref | vt_ui1.
Short far * pival; // vt_byref | vt_i2.
Long far * plval; // vt_byref | vt_i4.
Float far * pfltval; // vt_byref | vt_r4.
Double far * pdblval; // vt_byref | vt_r8.
Variant_bool far * pboolval; // vt_byref | vt_bool.
Scode far * pscode; // vt_byref | vt_error.
Cy far * pcyval; // vt_byref | vt_cy.
Date far * pdate; // vt_byref | vt_date.
BSTR far * pbstrval; // vt_byref | vt_bstr.
Iunknown far * ppunkval; // vt_byref | vt_unknown.
Idispatch far * ppdispval; // vt_byref | vt_dispatch.
Safearray far * pparray; // vt_array | *.
Variant far * pvarval; // vt_byref | vt_variant.
Void far * byref; // generic byref.
Char cval; // vt_i1.
Unsigned short uival; // vt_ui2.
Unsigned long ulval; // vt_ui4.
Int intval; // vt_int.
Unsigned int uintval; // vt_uint.
Char far * pcval; // vt_byref | vt_i1.
Unsigned short far * puival; // vt_byref | vt_ui2.
Unsigned long far * pulval; // vt_byref | vt_ui4.
NT far * pintval; // vt_byref | vt_int.
Unsigned int far * puintval; // vt_byref | vt_uint.
_ Variant_t is the encapsulation class of variant, and its value assignment can be forced type conversion. Its constructor will automatically process these data types.
# Include <comdef. h> must be added for use.
For example:
Long L = 222;
Ing I = 100;
_ Variant_t lval (L );
Lval = (long) I;
The use of colevariant is basically the same as that of the _ variant_t method. See the following example:
Colevariant V3 = "string", V4 = (long) 1999;
Cstring STR = (BSTR) v3.pbstrval;
Long I = v4.lval;

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.