Submission 62ad68cf...

ChallengeHex decoder
Submitter0x9e0ad99de20a444...
Submitted at2018-24-12
Gas used1039639
/**
 * 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) {
        uint len = bytes(input).length;
        uint index;
        output = new bytes(len/2);
        bytes32 slotString;
        bytes32 secondSlotString;
        for(uint i = 0; i < len ; i = i+64){
            uint numBytes = ((len-i)>=64)?64:len-i;
            for(uint j = 0; j < numBytes ;j = j+2){
                slotString = slotString>>8 | bytes(input)[j+i];
                secondSlotString = bytes(input)[j+i+1] | secondSlotString>>8;    
            }   
            slotString = bytes32((uint(slotString&0x4040404040404040404040404040404040404040404040404040404040404040)>>6)*9 + uint(slotString&0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F));
            secondSlotString = bytes32(uint(secondSlotString&0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F) + (uint(secondSlotString&0x4040404040404040404040404040404040404040404040404040404040404040)>>6)*9);
            slotString = bytes32(uint(slotString)*16 + uint(secondSlotString));
            numBytes = numBytes>>1;
            index = i>>1;
            for(j = 0;j<numBytes;j++){
                output[index+j] = bytes1(slotString<<8*(numBytes-1-j));
            }  
        }
    }
}