【问题标题】:Python style repr for char * buffer in c?c语言中char *缓冲区的Python样式repr?
【发布时间】:2012-07-21 01:11:33
【问题描述】:

我大部分时间都在 Python 中工作,因此我非常欣赏 repr() 函数,当传递任意字节字符串时,它会打印出人类可读的十六进制格式。最近我一直在用 C 做一些工作,我开始怀念 python repr 函数。我一直在互联网上搜索类似的东西,最好是void buffrepr(const char * buff, const int size, char * result, const int resultSize) 但我没有运气,有人知道这样做的简单方法吗?

【问题讨论】:

    标签: python c repr


    【解决方案1】:

    我通过依赖左侧带有流对象的“

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

    // 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转换为c字符串:

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

    这样称呼它:

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

    任何类都可以使用这个宏,只要它实现了“

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • sprintf 不好。请改用snprintf
      • 效果很好,但请注意,要让它在 Windows 上编译,您需要添加类似 #ifdef WIN32\n#define snprintf _snprintf\n#endif 之类的内容,微软似乎喜欢重命名函数!
      • 微软会重命名这样一个有用的函数并不奇怪,因为他们 typedef all pointers 我想他们对 C 的掌握并不太好。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2012-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-26
        • 2015-10-04
        • 2013-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多