Submission c0fd6463...

ChallengeHex decoder
Submitter0x53b21be84eece2e...
Submitted at2018-58-24
Gas used1518437
/**
 * 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 inp = bytes(input);
        uint len = inp.length / 2;
        uint8 b1;
        uint8 b2;
        output = new bytes(len);

        for (uint i = 0; i < len; i ++) {
            b1 = uint8(inp[i * 2]);
            b2 = uint8(inp[i * 2 + 1]);

            output[i] = byte((
                (b1 & 0xf) + (b1 / 64) * 9
            ) * 16 + (
                (b2 & 0xf) + (b2 / 64) * 9
            ));
        }
        return output;
    }
}