title: Convert uint24 to HEX string in Solidity
body: <p>I am trying to convert uint24 value of a kind <code>0x00ff08</code> to a human readable <code>string</code> with the same characters in Solidity smart contract which I am going to deploy on RSK. In my question about <a href="https://stackoverflow.com/questions/69312285/how-to-convert-bytes3-to-hex-string-in-solidity">bytes3 to hex string casting</a> I was advised for these purposes to use a function</p>
  <pre><code>function uint24tohexstr(uint24 i) public pure returns (string memory) {
          bytes memory o = new bytes(6);
          uint24 mask = 0x00000f;
          o[5] = bytes1(uint8tohexchar(uint8(i &amp; mask)));
          i = i &gt;&gt; 4;
          o[4] = bytes1(uint8tohexchar(uint8(i &amp; mask)));
          i = i &gt;&gt; 4;
          o[3] = bytes1(uint8tohexchar(uint8(i &amp; mask)));
          i = i &gt;&gt; 4;
          o[2] = bytes1(uint8tohexchar(uint8(i &amp; mask)));
          i = i &gt;&gt; 4;
          o[1] = bytes1(uint8tohexchar(uint8(i &amp; mask)));
          i = i &gt;&gt; 4;
          o[0] = bytes1(uint8tohexchar(uint8(i &amp; mask)));
          return string(o);
      }
  </code></pre>
  <p>I wanted to make use of a loop in that function and rewrote it like this</p>
  <pre><code>function uint24ToHexStr(uint24 i) public pure returns (string memory) {
          bytes memory o = new bytes(6);
          uint24 mask = 0x00000f; // hex 15
          for(uint k = 5; k &gt;= 0; k -= 1) {
            o[k] = bytes1(uint8ToHexCharCode(uint8(i &amp; mask)));
            i &gt;&gt;= 4;
          }
          return string(o);
      }
  </code></pre>
  <p>But unfortunately this function causes runtime error because on the last iteration unsigned integer <code>k</code> becomes <code>-1</code>. The first thing that crossed my mind was to increase k by one so that</p>
  <pre><code>        for(uint k = 6; k &gt;= 1; k -= 1) {
            o[k - 1] = bytes1(uint8ToHexCharCode(uint8(i &amp; mask)));
          }
  </code></pre>
  <p>Can anyone think of a more elegant way to achieve the same result?</p>