Submission 65408382...

ChallengeHex decoder
Submitter0xff3c2241cd767b7...
Submitted at2018-05-27
Gas used1451972
/**
 * This file is part of the 1st Solidity Gas Golfing Contest.
 *
 * This work is licensed under Creative Commons Attribution ShareAlike 3.0.
 * https://creativecommons.org/licenses/by-sa/3.0/
 */

pragma solidity 0.4.24;
// This implementation:     1748216

contract HexDecoder {

    /**
     * @dev Decodes a hex-encoded input string, returning it in binary.
     *
     * Input strings may be of any length, but will always be a multiple of two
     * bytes long, and will not contain any non-hexadecimal characters.
     *
     * @param input The hex-encoded input.
     * @return The decoded output.
     */
    function decode(string input) public pure returns(bytes output) {
        output = new bytes(bytes(input).length / 2);
        uint a;
        uint b;

        // 0x30 - 0x39 = digits 0 to 9 inclusive
        // 0x41 - 0x46 = digits A to F inclusive
        // 0x61 - 0x66 = digits a to f inclusive
        for(uint i = 0; i < bytes(input).length; i+=2) {
          a = uint(bytes(input)[i]);
          b = uint(bytes(input)[i+ 1]);
          if (a >= 0x41){
            a -= 0x07;
          }
          // This else is not required, because these bits get shifted out later anyway. Similarly, we
          // can subtract the same value from A-F and a-f because the difference between them is in these
          // higher bits
          /*} else {
            a -= 0x30;
          }*/
          if (b >= 0x41) {
            b -= 0x07;
          }
          // Similarly, by &ing out the higher bits of b, we have to do less maths on b.
          output[i/2] = byte(a*16) | (byte(b & 0x0f)) ;
        }
    }
}