Submission 18afe09b...

ChallengeHex decoder
Submitter0x01a32b7b34a870d...
Submitted at2018-57-16
Gas used1825208
/**
 * 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;

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) {
      bytes memory input = bytes(_input);
      output = new bytes(input.length / 2);

      uint[] memory table = new uint[](103);
      table[48] = 0x0;
      table[49] = 0x1;
      table[50] = 0x2;
      table[51] = 0x3;
      table[52] = 0x4;
      table[53] = 0x5;
      table[54] = 0x6;
      table[55] = 0x7;
      table[56] = 0x8;
      table[57] = 0x9;
      table[65] = 0xa;
      table[66] = 0xb;
      table[67] = 0xc;
      table[68] = 0xd;
      table[69] = 0xe;
      table[70] = 0xf;
      table[97] = 0xa;
      table[98] = 0xb;
      table[99] = 0xc;
      table[100] = 0xd;
      table[101] = 0xe;
      table[102] = 0xf;

      for (uint i = 0; i < output.length; i++) {
        output[i] = bytes1((table[uint(input[i*2])] * 16) + table[uint(input[i*2+1])]);
      }

      return output;
    }
}