-1

I have a CLinux device, that i need to transform some data. The input is something like

char mytest[] = "020441010C0000003131203131203131313103";

and i need to have

mytest2[] = {0x02,0x04,0x41,0x01,0x0C,0x00,0x00,0x00,0x31,0x31,0x20,0x31,0x31,0x20,0x31,0x31,0x31,0x31,0x03}

This is the code that i've tried, but it doesn't compile cause the sstream is not on the device OS.. Can some give me another solution to transform the data?

#include <iostream>
#include <sstream>


int main() {
std::string myStr = "1122AA010A";

std::stringstream ss;
int n;
for(int i = 0; i<myStr.length(); ) {
    std::istringstream(myStr.substr(i,2))>>std::hex>>n;
    ss<<(char)n;
    i += 2;
    }

std::string result = ss.str();

std::cout<<"\n"<<result<<"\n";
return 0;
}
AShelly
  • 34,686
  • 15
  • 91
  • 152
SE-LM
  • 1
  • 4

1 Answers1

1

Parsing hex is pretty easy. Convert each digit to its hex value, and combine them together into a single char.

int FromHexDigit(char c) //Returns a number from 0 to 15
{
    if(c >= '0' && c <= '9')
        return c-'0';
    else if(c >= 'A' && c <= 'F')
        return c-'A' + 10;
    else if(c >= 'a' && c <= 'f')
        return c-'a' + 10;
    else
        return -1; //Not a hex digit :(
}

Then the main loop becomes:

std::string result;
for(int i = 0; i<myStr.length(); i += 2) {
    char d1 = myStr[i], d2 = myStr[i+1]; //Those are the two consecutive hex digits
    int n = FromHexDigit(d1)*16 + FromHexDigit(d2); //Convert to a number
    result += (char)n; //Put into the result string
}

Note the i+=2 portion in the for loop header. We're processing the string in two byte chunks. There's no handling of the situation that the string has an odd number of characters.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
  • What do you mean with `convert each digit to its hex value` ? There's no way to work like with substrings, working with 2 digits at at time? ( cause they're already in hex ) – SE-LM Mar 19 '19 at 17:40
  • @SE-LM you can do a substring of size 2 then make a sstring with it then extract in hexa, but this is much more expensive – bruno Mar 19 '19 at 17:42
  • is strange to put the result in a string, a `vector` or equivalent seems more natural no ? – bruno Mar 19 '19 at 17:43