Submission 6671457f...

ChallengeHex decoder
Submitter0xff3c2241cd767b7...
Submitted at2018-43-25
Gas used1497696
/**
 * 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;
// This implementation:     1772072

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 >= 0x41){
              a -= 0x07;
            }
            // This else is not required, because these bits get shifted out later anyway. Similarly, we
            // can subtract the same value from A-F and a-f because the difference between them is in these
            // higher bits
            /*} else {
              a -= 0x30;
            }*/
            if (b >= 0x41) {
              b -= 0x07;
            }
            // Similarly, by &ing out the higher bits of b, we have to do less maths on b.
            output[i] = byte(a*16) | (byte(b & 0x0f)) ;
        }
    }
}