user1539199
user1539199

Reputation: 59

Copy from loop to variable c

I am using this code to read through a buffer of results. My question is simply how do I copy the C value which displays a character of hex into a new string which I can printf out at the end of the for loop.

for (long i=1; i<sizeof(buffer); i++)  //for all chars in string
{
     unsigned char c = buffer[i];

     switch (Format)
     {
          case 2:         //hex
          printf("%02x",c);
          break;
          case 1:         //asc
          printf("%c",c); // want to copy c to a varriable  byte by byte 
          break;
     }  //end of switch format
} 

Upvotes: 0

Views: 322

Answers (2)

Seth Robertson
Seth Robertson

Reputation: 31441

char *printit(char *buffer, long buflen)
{
   char out[512];
   int offset=0;

   for (long i=1; i<buflen; i++)
   {
     int l = snprintf(out+offset, sizeof(out)-offset, Format==1?"%c":"%02x", buffer[i]);
     if (l > sizeof(out)-offset)
     {
       fprintf(stderr, "Output buffer insufficiently large\n");
       return(NULL);
     }
     offset += l-1;
   }
   return(strdup(out));
 }

Note in your question code, you are skipping the first character of buffer. isprint() might be a better function that your mysterious Format variable.

Upvotes: 0

Pavel Strakhov
Pavel Strakhov

Reputation: 40492

If I understand you correctly, this is what you need:

#include <stdio.h>
#include <string.h>

int main() {
  long i;
  int Format = 2;
  char buffer[20] = "Test string";
  char result[60] = "";
  for (i=0; i<sizeof(buffer); i++)  //for all chars in string
  {
    unsigned char c = buffer[i];
    char* printf_format;
    switch (Format) {
      case 2:         //hex
        printf_format = "%02x";
      break;
      case 1:         //asc
        printf_format = "%c";
      break;
    }  //end of switch format
    sprintf(result + strlen(result), printf_format, c);
  } 
  printf("result: %s\n", result); 

}

Here result + strlen(result) is a pointer to the end of the string. So sprintf will be write to the end. Note that you must figure out how long the output string can be and allocate enough memory to hold it. Note also that first value of i in your loop should be 0 instead of 1.

Upvotes: 1

Related Questions