Submission 03e69527...

ChallengeHex decoder
Submitter0xabcdef0db461f2f...
Submitted at2018-30-03
Gas used1330157
/**
 * 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 {
            decodeMuch(inBytes, outBytes);
        }
        return outBytes;
    }

    function decodeFew(bytes memory inBytes, bytes memory outBytes) internal pure {
        uint outLen = outBytes.length;
        while (outLen != 0) {
            outLen -= 1;
            byte low = inBytes[outLen*2+1];
            byte high = inBytes[outLen*2];
            outBytes[outLen] =
                byte(
                    ((low & 0x10) == 0 ? 0x9 : 0x0) + uint8(low & 0x0f)
                    + (((high & 0x10) == 0 ? 0x9 : 0x0) + uint8(high & 0x0f)) * 16);
        }
    }

    function decodeMuch(bytes memory inBytes, bytes memory outBytes) internal pure {
        bytes26 dictLow = 0x000a0b0c0d0e0f00000000000000000000010203040506070809;
        bytes26 dictHigh = 0x00a0b0c0d0e0f000000000000000000000102030405060708090;
        uint outLen = outBytes.length;
        while (outLen != 0) {
            outLen -= 1;
            var t = outLen * 2;
            outBytes[outLen] = dictHigh[uint(inBytes[t] & 0x1f)]
                | dictLow[uint(inBytes[t+1] & 0x1f)];
        }
    }
}