title: Write hex array to the file as string in C/C++
body: <p>This is a frequently question but I could not find appropriate answer.</p>
  
  <p>I have a char array containing HEX values. I need to write this array in a text file "as a string".</p>
  
  <hr>
  
  <p>My understanding of HEX not being stored in the files (looked garbage data) was flawed. In Hex editor I could see the data.</p>
  
  <p>My Hex array is actually integer array and not characters. This I need to take into consideration.</p>
  
  <hr>
  
  <p>I tried this:</p>
  
  <pre><code>   FILE * out = fopen(out_file_name, "w");
     char *in = (char*)malloc(sizeof(char) * num_encryption * 16);
     ....
     fwrite(in, sizeof(char), num_encryption*16 + 1, out);
  </code></pre>
  
  <p>I also tried <code>stream</code> but it again prints garbage in text files.</p>
  
  <p>The <code>in</code> array contains the HEX strings like this: <code>21c169ea622e7d52ecd35423f4c3c9f4</code>, and there are 32 lines (<code>num_encryption=32</code>) in total.</p>
  
  <p>I also tried something like this:    </p>
  
  <pre><code>std::ofstream outfile(argv[21]);
  if(outtfile.is_open()){
    //outtfile.write(wo, sizeof(char)*(num_encryption*16+1));
    for(int k = 0; k &lt; num_encryption; k++){
        for(int j = 0; j &lt; 16; ++j){
           outfile &lt;&lt; static_cast&lt;unsigned char&gt;(wo[j + k*16] &amp; 0xff);
        }
     outtfile &lt;&lt; std::endl;
    }
  }
  </code></pre>
  
  <p>Even the commented part did not work properly.
  Any suggestions?</p>
  
  <hr>
  
  <p>Solution</p>
  
  <hr>
  
  <p>I just redirected the output (which was fine) to the file:</p>
  
  <pre><code>FILE * out = fopen(out_file_name, "w");
  for(int k = 0; k &lt; num_encryption; k++){
      for(int j = 0; j &lt; 16; ++j){
         fprintf(outfile, "%02x", wo[j + k*16] &amp; 0xff);
         }
      fprintf(outfile, "\n");
   }
  fclose(outfile);
  </code></pre>
  
  <p>I am not sure if this is the most elegant solution,but it works for me. If you know anything better then please add here.</p>