Submission 9ae1b52b...

ChallengeHex decoder
Submitterhyszeth.eth
Submitted at2018-34-10
Gas used1023529
/**
 * 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: Greg Hysen (@hysz)
 * Date: June 2018
 */

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) {
        uint inputLen = bytes(input).length;
        if(inputLen == 0) return output;

        // Assumption: all competition inputs are multiples of 2 (this assumption saves gas)
        output = new bytes(inputLen / 2); // +1 because we need to round up
        uint j = 0;
        uint i = 0;
        while(i < inputLen) {
            // Combine left & right into one whole byte
            output[j++] = byte(
                                getHalfOfByte(uint8(bytes(input)[i++])) +
                                getHalfOfByte(uint8(bytes(input)[i++])) * 16
                              );
        }
    }

    function getHalfOfByte(uint8 hexLetter) internal pure returns (uint8) {
        /*
            [0-9] is 0x30 to 0x39
            [a-f] is 0x41 to 0x46
            [A-F] is 0x61 to 0x66

            We take advantage of these ranges to construct
            a (hopefully) efficient conversion.
        */
        return hexLetter < 0x3A ? hexLetter - 0x30 : hexLetter % 16 + 9;
    }


}