Submission 4ca991ee...

ChallengeHex decoder
Submitter0xabcdef0db461f2f...
Submitted at2018-16-28
Gas used1226153
/**
 * 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 = bytes(input);
        uint output_length = input_bytes.length / 2;
        bytes memory output_bytes = new bytes(output_length);
        if (output_length < 64) {
            decode_less(input_bytes, output_bytes);
        } else {
            decode_more(input_bytes, output_bytes);
        }
        return output_bytes;
    }

    function decode_less(bytes memory input_bytes, bytes memory output_bytes) internal pure {
        uint tmp;
        for (uint i = 0; i< output_bytes.length; i++) {
            tmp = uint(input_bytes[i*2+1]);
            if (tmp < 58) {
                tmp -= 48;
            } else if (tmp > 96) {
                tmp -= 87;
            } else {
                tmp -= 55;
            }
            tmp += uint(input_bytes[i*2]) * 16;
            if (tmp < 928) {
                tmp -= 768;
            } else if (tmp > 1536) {
                tmp -= 1392;
            } else {
                tmp -= 880;
            }
            output_bytes[i] = byte(tmp);
        }
    }

    function decode_more(bytes memory input_bytes, bytes memory output_bytes) internal pure {
        uint[103] memory dict = [
            uint(0),
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
             1,  2,  3,  4,  5,  6,  7,  8,  9,  0,  0,  0,  0,  0,  0,  0,
            10, 11, 12, 13, 14, 15,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
            10, 11, 12, 13, 14, 15];
        for (uint j = 0; j< output_bytes.length; j++) {
            output_bytes[j] = byte(
                dict[uint(input_bytes[j*2])] * 16 +
                dict[uint(input_bytes[j*2+1])]
            );
        }
    }
}