EDITED: I'm writing a function in C++ which should take a hex string and should convert it to unicode string using c++. the conversion that I made using stream is not giving desired output. Could you please suggest a solution?
And If I make it as hardcoded unicode(like "e820" to "\u00e8\u0020") then works, but how to make this at run time?
Example 1:
- input hex string: 6880d7a5876b2b9b
- Expected output: h×¥k+
- current output with result: hÇ╫Ñçk+¢
- current output with Temp : h×¥k+
Example 2:
- input hex string: e820b19b7ae506ff
- Expected output: è ±zåÿ
- current output with result: Φ ▒¢zσ♠
- current output with Temp : è ±zåÿ
My code sample:
//Hex string that I have
std::string str( "6880d7a5876b2b9b" );
std::string Temp( "\u00e8\u0020\u00b1\u009b\u007a\u00e5\u0006\u00ff" );
std::string result;
//Take 2 bytes and convert it to ascii
for (int i = 0; i < (int)str.size(); i += 2)
{
std::istringstream iss(str.substr(i, 2));
int temp;
iss >> std::hex >> temp;
result += static_cast<char>(temp);
}
std::cout << result << std::endl;
std::cout << Temp << std::endl;
After a weeks struggle I was able to find the solution using boost lib: Fix is as below:
std::string HexString("6880d7a5876b2b9b"); //Hex string as input
std::string UnicodeString;
//Take a char i.e 2 chars in hex string
for (int i = 0; i < ( int )HexString.size(); i += 2)
{
//Convert to int from hex
std::istringstream iss( HexString.substr( i, 2 ) );
unsigned int temp;
iss >> std::hex >> temp;
//Convert to \uxxx unicode
std::string Utf8Char = boost::locale::conv::utf_to_utf<char>( &temp, (&temp + 1) );
UnicodeString.append( Utf8Char );
}
std::cout<<"UnicodeString:"<<UnicodeString<<std::endl