Submission b97d6270...

ChallengeHex decoder
Submittermichaelsproul.eth
Submitted at2018-36-03
Gas used1633531
/**
 * 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/
 *
 * Implementation by Michael Sproul (https://sproul.xyz)
 */

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 inputBytes = bytes(input);
        uint n = inputBytes.length;
        uint m = n / 2;
        output = new bytes(m);
        //uint x;
        //uint y;
        for (uint i = 0; i < m; i++) {
            // ith byte from characters c = 2i and c = 2i + 1
            // This beaut little formula works because only '0'-'9' have bit 0x10 set,
            // so when you add 9 to them you get 25 + i.
            // For 'a'-'f' and 'A'-'F', the + 9 takes 0x41 to 0x01 to 10 and so on.
            //x = ;
            //y = ;
            // x = 16 * (((x & 0x1F) + 9) % 25);
            // y = ((y & 0x1F) + 9) % 25;
            output[i] = byte(
                16 * addmod(uint(inputBytes[i + i]) & 0x1F, 9, 25) |
                addmod(uint(inputBytes[i + i + 1]) & 0x1F, 9, 25)
            );
        }
    }
}