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
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;
}
}
}
-
2
-
2That 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 -
1Not 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
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.