Submission f71b36c9...

ChallengeHex decoder
Submitter0xabcdef0db461f2f...
Submitted at2018-41-01
Gas used391215
/**
 * 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 inBytes = bytes(input);
        uint outLen = inBytes.length / 2;
        if (outLen == 0) { return; }
        bytes memory outBytes = new bytes(outLen);
        assembly {
            let inPtr := add(inBytes, 0x20)
            let outPtr := add(outBytes, 0x20)
            let outPtrEnd := add(outPtr, outLen)
            for { } lt(outPtr, outPtrEnd) { } {
                // (((ord(char) & 0x1F) + 9) % 25)
                let tmp := and(mload(sub(inPtr, 0x1e)), 0xff)
                let sum := mod(add(and(tmp, 0x1f), 0x09), 0x19)
                tmp := and(mload(sub(inPtr, 0x1f)), 0xff)
                sum := add(sum, mul(mod(add(and(tmp, 0x1f), 0x09), 0x19), 16))
                mstore8(outPtr, sum)
                inPtr := add(inPtr, 0x2)
                outPtr := add(outPtr, 0x1)
            }
        }
        return outBytes;
    }
}