Submission 8cb218ca...

ChallengeHex decoder
Submitter0xff2c5414a8f9d1c...
Submitted at2018-43-08
Gas used1212152
/**
 * 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) {
        byte left;
        byte right;
        uint16 bits;
        uint16 mask1 = 0x0f0f;
        uint16 mask2 = 0x4040;
        uint256 len = bytes(input).length;
        output = new bytes(len/2);
        for (uint i; i < len; i = i + 2) {
            left = bytes(input)[i];
            right = bytes(input)[i+1];
            bits = (uint16(left) * 256) + uint16(right);
            bits = (bits & mask1) + ((bits & mask2) >> 6) * 9;
            output[i/2] = byte(uint8((bits >> 4) + bits));
        }
    }
}