title: convert decimal to hex, add to byte array
body: <p>I am working on some image conversion in objective C, for iOS, and having some difficulties in saving the total image size in a byte array..</p>
  
  <p>I did some searching, and stackoverflow has many questions with conversion from decimal to hex, but all of them explain how to print hex value using <code>%x</code> and printf(or NSLog), which is not what I want.</p>
  
  <p>I have an image with size 2500</p>
  
  <pre><code>int totalSize  = 2500;
  </code></pre>
  
  <p>I want to add this size to specific index in image header</p>
  
  <pre><code>UInt8 headerData[HEADER_SIZE];
  memset(headerData, 0, HEADER_SIZE);
  
  //2500 dec  = 9C4 hex
  headerData[2]   = 0xC4;
  headerData[3]   = 0x09;
  headerData[4]   = 0x00;
  headerData[5]   = 0x00;    //image size total 4 bytes
  </code></pre>
  
  <p>I found <a href="https://stackoverflow.com/questions/4085612/converting-an-int-to-a-2-byte-hex-value-in-c">this</a> thread and tried it out</p>
  
  <pre><code>char hexval[5];
  memset(hexval, 0, 5);
  if (totalSize &lt;= 0xFFFF){
      sprintf(&amp;hexval[0], "%0x", totalSize);
  }
  
  printf("%x %x %x %x", hexval[0], hexval[1], hexval[2], hexval[3]);
  </code></pre>
  
  <p>and it printed</p>
  
  <pre><code>36 36 33 32
  </code></pre>
  
  <p>which is not the correct value, or am I missing something obvious here?</p>
  
  <p><strong>EDIT:</strong> Sorry, forgot put the endianness part.. I want to save in little endian format. </p>
  
  <p>Note : I am adding a C tag also, since a C solution is applicable here too..</p>