5

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?

3 Answers 3

1

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;
    }
  }
}
3
  • 2
    sprintf is bad. use snprintf instead. Jul 22, 2012 at 16:03
  • 2
    That worked, perfectly, note though to get it to compile on windows you need to add something like #ifdef WIN32\n#define snprintf _snprintf\n#endif Microsoft seems to love to rename functions! Jul 22, 2012 at 16:33
  • 1
    Not too surprising that Microsoft would rename such a useful function, since they typedef all pointers I imagine their mastery of C isn't too great. Oct 28, 2015 at 15:51
0

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

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.