Submission 633a6fd8...

ChallengeHex decoder
Submitter0x1dba1131000664b...
Submitted at2018-07-26
Gas used74452
/**
 * 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/
 *
 * Author: Jordi Baylina
 */

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) {
        assembly {
            for {
                let l := mload(input)
                if and(l, 1) { revert(0,0) }
                let p := add(input, 32)
                let pend := add(p, l)
                let outp := add(output, 32)
                mstore(output, div(l,2))
            } lt(outp, pend) {
            } {
                let v := mload(p)
                let d := and(v, 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f)
                let d1 := div(and(v, 0x4040404040404040404040404040404040404040404040404040404040404040),8)
                let d2 := div(d1,8)
                d := add(d, add(d1,d2))

                d := and(add(div(d, 0x10), d),0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff)
                d := and(add(div(d, 0x100), d), 0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff)
                d := and(add(div(d, 0x10000), d), 0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff)
                d := and(add(div(d, 0x100000000), d), 0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff)
                d := add(div(d, 0x10000000000000000), d)
                d := mul(d, 0x100000000000000000000000000000000)

                mstore(outp, d)
                outp := add(outp, 16)
                p := add(p,32)
            }
        }

    }
}