0
votes

I am using wxWidgets with c++. I have a wxTextCtrl in which the user inputs a set of bytes in hex format separated by space. I want to get them in unsigned char array. How can I convert from a string like "AB D3 4F A A1 0B" to get the resulting array: [171, 211, 79, 10, 161, 11]?

3

3 Answers

2
votes

I would use wxStringTokenizer to break up the string into individual hexes, then sscanf to convert them into numeric values.

Something like this:

std::vector<unsigned char> vec;
wxStringTokenizer tkz(thetextCtrl->GetValue(), wxT(" "));
while ( tkz.HasMoreTokens() )
{
    wxString token = tkz.GetNextToken();
    unsigned char v;
    sscanf(token.c_str(),"%x",&v)
    vec.push_back( v );
}
1
votes

Instead of using a sscanf to convert Hex in integer you can also use the ToULong operation of a wxString in base 16.

wxString token = tkz.GetNextToken();
unsigned long ulVal;

if (token.ToULong(&ulVal, 16) == true)
{
  vec.push_back( (unsigned char)v );
}
else
{
  // A default value for example ...
  vec.push_back( (unsigned char)0 );
}
0
votes

You can also use boost::tokenizer to split string into tokens and this to convert string values to hex values.