Submission 52e5d9de...

ChallengeHex decoder
Submitter0xff3c2241cd767b7...
Submitted at2018-05-24
Gas used1610932
/**
 * 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) {
        output = new bytes(bytes(input).length / 2);
        uint8 a;
        uint8 b;

        // 0x30 - 0x39 = digits 0 to 9 inclusive
        // 0x41 - 0x46 = digits A to F inclusive
        // 0x61 - 0x66 = digits a to f inclusive
        for(uint i = 0; i < output.length; i++) {
          a = uint8(bytes(input)[i*2]);
          b = uint8(bytes(input)[i*2 + 1]);
            if (a >= 0x61){
              a -= 0x57;
            } else if (a >= 0x41) {
              a -= 0x37;
            } else {
              a -= 0x30;
            }
            if (b >= 0x61){
              b -= 0x57;
            } else if (b >= 0x41) {
              b -= 0x37;
            } else {
              b -= 0x30;
            }
            output[i] = byte(a*16) | byte(b);
        }
    }
}