Submission 986c31e3...

ChallengeHex decoder
Submitter0xabcdef0db461f2f...
Submitted at2018-54-03
Gas used1215527
/**
 * 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) {
        bytes memory inBytes = bytes(input);
        uint outLen = inBytes.length / 2;
        if (outLen == 0) {
            return;
        }
        bytes memory outBytes = new bytes(outLen);
        if (outLen <= 32) {
            decodeFew(inBytes, outBytes);
        } else {
            decodeMore(inBytes, outBytes);
        }
        return outBytes;
    }

    function decodeFew(bytes memory inBytes, bytes memory outBytes) internal pure {
        uint outLen = outBytes.length;
        while (outLen != 0) {
            outLen -= 1;
            uint tmp = uint(inBytes[outLen+outLen+1]);
            if (tmp < 58) {
                tmp -= 48;
            } else if (tmp > 96) {
                tmp -= 87;
            } else {
                tmp -= 55;
            }
            tmp += uint(inBytes[outLen+outLen]) * 16;
            if (tmp < 928) {
                tmp -= 768;
            } else if (tmp > 1536) {
                tmp -= 1392;
            } else {
                tmp -= 880;
            }
            outBytes[outLen] = byte(tmp);
        }
    }

    function decodeMore(bytes memory inBytes, bytes memory outBytes) 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];
        uint j = outBytes.length;
        while (j != 0) {
            j -= 1;
            outBytes[j] = byte(
                dict[uint(inBytes[j+j])] * 16 +
                dict[uint(inBytes[j+j+1])]
            );
        }
    }
}