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;
}
}
}
最简单的方法是使用%x
和%X
格式说明符的printf()
/ sprintf()
。
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 ac 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 ac 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.