Submission 92593b6b...

ChallengeHex decoder
Submitter0xff3c2241cd767b7...
Submitted at2018-54-24
Gas used2404013
/**
 * 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) {
        output = new bytes(bytes(input).length / 2);
        uint8 a;
        uint8 b;
        uint8[3] memory offsets;
        offsets[0] = 0x30;
        offsets[1] = 0x07;
        offsets[2] = 0x20;

        for(uint i = 0; i < output.length; i++) {
          uint j = 0;
          a = uint8(bytes(input)[i*2]);
          b = uint8(bytes(input)[i*2 + 1]);
          while (true){
            if (a >= 0x10){
              a -= offsets[j];
            }
            if (b >= 0x10){
              b -= offsets[j];
            }
            j += 1;
            if (a <=0x0f && b <= 0x0f){
              output[i] = byte(a*16) | byte(b);
              break;
            }
          }
        }
    }
}