for the most part I work in Python, and as such I have developed a great appreciation for the repr() function which when passed a string of arbitrary bytes will print out it's human readable hex format. Recently I have been doing some work in C and I am starting to miss the python repr function. I have been searching 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 have ha no luck, is anyone aware of a simple way to do this?

有帮助吗?

解决方案

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

you can loop thru (very simply) like this:

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;
    }
  }
}

其他提示

The most simple way would be printf()/sprintf() with the %x and %X format specifiers.

I have approached this problem in part by relying on the "<<" operator with a stream object on the left side. If you implement this operator on your classes, those classes (and the standard ones) will work with the following solution.

Next we define a function and a macro that converts your object into a c string that can be used in a 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 the std::string to a c string:

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

Call it like this:

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top