john-charles john-charles - 9 days ago 6
Python Question

Python style repr for char * buffer in c?

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?

Answer

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