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?

4

3 回答 3

1

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

你可以像这样循环(非常简单):

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;
    }
  }
}
于 2012-07-22T15:59:35.607 回答
0

最简单的方法是printf()/sprintf()使用%xand%X格式说明符。

于 2012-07-22T15:59:48.803 回答
0

我部分地通过依赖左侧带有流对象的“<<”运算符来解决这个问题。如果你在你的类上实现这个操作符,这些类(和标准类)将使用下面的解决方案。

接下来,我们定义一个函数和一个宏,将您的对象转换为可在 printf 函数中使用的 ac 字符串:

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

    return ss.str();
}

接下来我们有一个封装了上述函数的宏,将std::string转换为ac字符串:

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

像这样称呼它:

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

任何类都可以使用这个宏,只要它实现了“<<”,就像任何 Python 类都可以实现它自己的 repr() 方法一样。

于 2016-11-30T01:36:06.967 回答