(Urgent)Problem of changing Cstring to Hex

Started by
2 comments, last by mattd 14 years, 6 months ago
Hi all, I am currently trying to change CString to hex, but I can't find the code works, any advice? I need urgent help, thanks. m_strDataToWrite="TESTING"; CStringToUchar(m_strDataToWrite,ucDataToWrite,&ulBufferLen); void MifareEncFrameApp::CStringToUchar(CString str, UCHAR *ucBuffer, ULONG *ulBufferLen) { int Length = 0; int DataLength = 0; char cstr[3] = {}; int hexval=0; CString str; CString hexstrOutput; CString p; p = str.GetBuffer(1); int len = str.GetLength(); for (int n = 0 ; n < len ; n++) { TCHAR tmp[4] = { 0 }; _stprintf(tmp, TEXT("%02x "), p[n]); hexstrOutput += tmp; } str.ReleaseBuffer(); DataLength = str.GetLength() / 2; for ( int i = 0; i<DataLength; i++) { cstr[0] = str[2*i]; cstr[1] = str[2*i+1]; sscanf( cstr, "%02x", &hexval ); ucBuffer= static_cast<UCHAR>(hexval); } *ulBufferLen = DataLength; }
Advertisement
You are hiding str with a local variable with same name.
Also, you generate hexstrOutput, but never use it.

You appear to be confusing multiple routines together. Which are you trying to do?
Binary data (as CString) -> hex representation, or hex representation -> binary data (as ULONG buffer)?
Hi thanks for the reply, I think i made mistake while pasting the code. Actually what i am trying to do is:

str="TESTING";

Then i changed the m_strDataToWrite to hex string using the following code:
<code>
p = str.GetBuffer(1);
int len = str.GetLength();

for (int n = 0 ; n < len ; n++)
{
TCHAR tmp[4] = { 0 };
_stprintf(tmp, TEXT("%02x "), p[n]);

hexstrOutput += tmp;
</code>

I did changed the str to hex string (TESTING->54 45 53 54 49 4e 47).

Next I wish to change the hex string to unsigned char and put it into ucBuffer.But i was unable to do it . Any advice?
If you're trying to get a UCHAR buffer from a CString, just use the CString's LPCTSTR conversion operator.

Check this article out, specifically that section.

However if you have UNICODE defined, LPCTSTR is going to be a wide string, so you'll need to either take note of this (i.e, use WCHARs), or use a conversion function like WideCharToMultiByte with your own UCHAR buffer.

All that said, there's no reason to write your own 'CStringToUchar' function. CString already supports giving (read-only) access to its underlying character data, as already mentioned. If you need your own instance of the data (i.e., for future modifications), you can _tcscpy it into your own buffer (or, if you have Unicode set, convert it to a UCHAR buffer explicitly as mentioned).

[Edited by - mattd on November 11, 2009 6:51:31 AM]

This topic is closed to new replies.

Advertisement