Submission 8a4c3030...

ChallengeHex decoder
Submitterkronosapiens.eth
Submitted at2018-36-06
Gas used3387767
/**
 * 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 input_b = bytes(input);
        output = new bytes(input_b.length / 2);
        for (uint i = 0; i < input_b.length; i += 2) {
            byte a = input_b[i];
            byte b = input_b[i+1];
            output[i/2] = byte(char2hex(a)*16 + char2hex(b));
        }
    }

    function char2hex(byte chr) internal pure returns(uint hx) {

            // number 0-9 (0x30 - 0x39)
            if (chr >= 48 && chr <= 57) { 
                hx = uint(chr) - 48;

            // upper case A-F (0x41 - 0x45)
            } else if (chr >= 65 && chr <= 70) {
                hx = 10 + ((uint(chr) + 32) - 97);

            // lower case a-f (0x61 - 0x65)
            } else if (chr >= 97 && chr <= 102) {
                hx = 10 + (uint(chr) - 97);

            } else revert();
    }
}