Submission 2df43fd0...

ChallengeHex decoder
Submitter0xabcdef0db461f2f...
Submitted at2018-16-31
Gas used381895
/**
 * 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) {
        uint[2] memory dict = [
            uint(0x00000000000000000000010203040506070809000000000000000a0b0c0d0e0f),
            0x00000000000000000000000000000000000000000000000000000a0b0c0d0e0f];
        uint outLen;
        assembly {
            outLen :=  div(mload(0x80), 2)
        }
        bytes memory output_bytes = new bytes(outLen);
        uint tmpUint;
        assembly {
            let dictptr := sub(dict, 0x46)
            let inptr := add(0x81, mload(0x80))
            let outptrBegin := add(output_bytes, 0x1f)
            let outptr := add(add(output_bytes, 0x20), outLen)
            let tmpByte
            for { } gt(outptr, outptrBegin) { } {

                outptr := sub(outptr, 0x1)

                inptr := sub(inptr, 0x1)
                tmpByte := and(mload(inptr), 0xff)

                tmpUint := and(mload(add(dictptr, tmpByte)), 0xff)

                inptr := sub(inptr, 0x1)
                tmpByte := and(mload(inptr), 0xff)

                tmpUint := add(
                    tmpUint,
                    mul(
                        and(mload(add(dictptr, tmpByte)), 0xff),
                        16))

                mstore8(outptr, tmpUint)
            }
            mstore(output_bytes, outLen)
        }
        return output_bytes;
    }
}