Submission 6d5c8640...

ChallengeHex decoder
Submitter0x1dba1131000664b...
Submitted at2018-46-26
Gas used645318
/**
 * 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, 1)
                let pend := add(p, l)
                let outp := add(output, 32)
                mstore(output, div(l,2))
            } lt(p, pend) {
            } {
                let c1 := and(mload(p), 0xff)
                c1 := sub(c1,48)
                if gt(c1, 9) { c1 := sub(c1, 7) }
                if gt(c1, 15) { c1 := sub(c1, 32) }
                if gt(c1, 15) { revert(0,0) }
                p := add(p,1)

                let c2 := and(mload(p), 0xff)
                c2 := sub(c2,48)
                if gt(c2, 9) { c2 := sub(c2, 7) }
                if gt(c2, 15) { c2 := sub(c2, 32) }
                if gt(c2, 15) { revert(0,0) }
                p := add(p,1)

                mstore8(outp, add(mul(c1,16), c2))
                outp := add(outp, 1)
            }
        }
    }
}