Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert hex string to Chinese chars

Status
Not open for further replies.

Lorey

Programmer
Feb 16, 2003
88
SG
Hi experts!

Is there a more decent way to convert below example hex strings to actual chinese chars other than code below?

Code:
	// sample hex string		
	std::string str = "\\0030\\31\\70ED\\83AB\\6279\\5FD2\\004c\\0045\\0046";
	const unsigned int MAX_LEN = 300;

	wchar_t* wStr = new wchar_t[(MAX_LEN)+1]; 
	memset(wStr,0x00,(MAX_LEN)+1);
	unsigned short wStrCtr = 0;
	for(unsigned int i = str.find("\\", 0); i != std::string::npos; i = str.find("\\", i))
	{
		unsigned int nextPos = str.find("\\", i+1);

		std::string st = str.substr(i+1,nextPos-(i+1));

		//validate the hex string
		if (4 != st.length() )
		{
			std::ostringstream os;
			os << std::setfill('0') << std::setw(4) << (st);
			st = os.str().c_str();
		}

		unsigned int val=0;
		sscanf (st.c_str(), "%x", &val);

        unsigned char highByte = static_cast<unsigned char>((val & 0xFF00) >> 8);
        unsigned char lowByte = static_cast<unsigned char>(val & 0xFF);

		wStr[wStrCtr++] = ((highByte & 0x00FF) << 8) | ( lowByte & 0x00FF);

		i++;
	}

	//need to do this else there will be garbage at the end
	wStr[wStrCtr] = 0;

	// Get the byte length of wStr
	int byteLen = WideCharToMultiByte (CP_OEMCP,0,wStr,-1,0,0,0,0);
	char *finalMessage = new char[byteLen+1];
	memset(finalMessage,0x00,byteLen+1);
	WideCharToMultiByte (CP_OEMCP, 0, wStr, -1, finalMessage, byteLen, 0, 0);
	finalMessage[byteLen] = 0;
	
	SetDlgItemText(IDC_EDIT1, finalMessage);			
	UpdateData(false);		

	delete [] wStr;
	delete [] finalMessage;
 
You can use

1) strtok to split the strings
2) strtol to convert them to numbers

Are you sure it is MBCS and not Unicode? If it is, then assign the values straight to a TCHAR (wchar_t).

If it is Unicode, it says

01????LEF
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top