Submission 3dcef9ed...

ChallengeHex decoder
Submittersggc.yuetloo.eth
Submitted at2018-57-30
Gas used2067090
/**
 * This contract was a modified version of the original from 
 * https://github.com/arachnid/sggc.git
 *
 * 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/
 */


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) {
        assert(bytes(input).length % 2 == 0);

        if( bytes(input).length == 0 ) return;

        output = new bytes(bytes(input).length / 2);

        uint8[] memory lookup = new uint8[](103);
        lookup[48] = 0;
        lookup[49] = 1;
        lookup[50] = 2;
        lookup[51] = 3;
        lookup[52] = 4;
        lookup[53] = 5;
        lookup[54] = 6;
        lookup[55] = 7;
        lookup[56] = 8;
        lookup[57] = 9;
        lookup[65] = 10;
        lookup[66] = 11;
        lookup[67] = 12;
        lookup[68] = 13;
        lookup[69] = 14;
        lookup[70] = 15;
        lookup[97] = 10;
        lookup[98] = 11;
        lookup[99] = 12;
        lookup[100] = 13;
        lookup[101] = 14;
        lookup[102] = 15;

        uint maxLoop = output.length/4;
        for(uint i = 0; i < maxLoop*4; i+=4) {
           output[i] = byte((lookup[uint(bytes(input)[i * 2])] << 4) | lookup[uint(bytes(input)[i * 2 + 1])]);
           output[i+1] = byte((lookup[uint(bytes(input)[(i+1) * 2])] << 4) | lookup[uint(bytes(input)[(i+1) * 2 + 1])]);
           output[i+2] = byte((lookup[uint(bytes(input)[(i+2) * 2])] << 4) | lookup[uint(bytes(input)[(i+2) * 2 + 1])]);
           output[i+3] = byte((lookup[uint(bytes(input)[(i+3) * 2])] << 4) | lookup[uint(bytes(input)[(i+3) * 2 + 1])]);
        }

        // loop for remainder
        for(i = 4 * maxLoop; i < output.length; i++) {
           output[i] = byte((lookup[uint(bytes(input)[i * 2])] << 4) | lookup[uint(bytes(input)[i * 2 + 1])]);
        }
    }
}