Python style representation for char * buffer in c?

for the most part, I work in Python, and so I got a lot of appreciation for a function repr()that, when passing a string of arbitrary bytes, will output it in XML format for reading. I have been working on C recently and am starting to skip the python function repr. I searched on the Internet for something similar to it, preferably something like void buffrepr(const char * buff, const int size, char * result, const int resultSize)But I'm out of luck, does anyone know an easy way to do this?

+5
source share
3 answers

sprintf (char *, "% X", b);

you can execute the loop (very simple) as follows:

void buffrepr(const char * buff, const int size, char * result, const int resultSize)
{
  while (size && resultSize)
  {
    int print_count = snprintf(result, resultSize, "%X", *buff); 
    resultSize -= print_count;
    result += print_count;
    --size;
    ++buff;

    if (size && resultSize)
    {
      int print_count = snprintf(result, resultSize, " ");
      resultSize -= print_count;
      result += print_count;
    }
  }
}
+1
source

The easiest way is printf()/ sprintf()with format specifiers %xand %x.

0
source

, "< . , ( ) .

Next, we define a function and a macro that converts your object to a string c, which can be used in the printf function:

// return a std::string representation of argument
template <typename T> std::string string_repr(T myVar)
{
    std::stringstream ss;
    ss << myVar;

    return ss.str();
}

Next, we have a macro that encapsulates the above function, converting std :: string to string c:

#define c_repr(_myVar) (string_repr(_myVar).c_str())

Name it as follows:

printf("prevXfm = %s  newXfm = %s\n", c_repr(prevXfm), c_repr(newXfm));

Any class can be created to work with this macro if it implements "<<", just like any Python class can implement its own repr () method.

0
source

All Articles