1

I have data in zeros and ones only, I want to tightly pack the data and store it to reduce the gas cost. Also I should be able to retrieve the original data from the tightly packed.

pragma solidity ^0.4.17;
contract TightPack {
    // gas 422749
    uint[] a;
    uint[] c;

    // function to pack
    function pack(uint[] b) public{
        uint l = b.length;
        delete a;

        // Extract first element and allocate a new slot
        for(uint i=0;i<l/256;i++){

            uint j = i * 256;
            uint temp = b[j] << 255;
            // b[i] = b[i] << 7;
           // Fill until new slot is full i.e 254 values
            for(j=j + 1;j < i * 256 + 256;j++){
                temp = (b[j] << (255 - (j%256))) | temp;
            }
            a.push(temp);
        }
        // if few values are reamining at the end, allocate a new one 
        if (l%256 > 0){
           uint k= (l/256)*256;
            uint val = (b[k] << 255);
            for(k=k+1; k < l;k++){
                val = (b[k] << (255 - (k%256))) | val;
            }
            a.push(val); 
        }

    }

    function unpack() public {
        uint l = a.length;
        delete c;
        // remove a value from array
        for(uint i = 0;i < l;i++){
            uint temp = a[i];
            // Parse the whole value to get 255 values
            for(uint j=0;j < 256;j++){
                c.push(temp >> (255 - j) & 1);
            }
        }
    }

    function get_packed() public view returns(uint[]){
        return a;
    }

    function get_unpacked() public view returns(uint[]){
        return c;
    }

}

The packing dosent work after 1000 values, while the unpacking doesn't work after 380 values.

What is the reason for this?

5
  • What do you mean by "doesn't work"? Can you provide the txs hashes? – Elisha Drion Apr 30 '18 at 22:01
  • transaction It is out of gas. Does the gas increase with the number of the iterations in the loop. (If a for loop with 10 iterations consumes 100 gas, then the same loop with 20 iterations consumes more than 200 gas ?) – Yashwanth May 1 '18 at 14:53
  • Yes, obviously. Be sure that you set the gas limit high enough and that you don't hit the gas limit per block too. – Elisha Drion May 1 '18 at 15:03
  • If a for loop with 10 iterations consumes 100 gas, then the same loop with 20 iterations consumes more than 200 gas. Why is this? What is the reason for this? – Yashwanth May 1 '18 at 16:01
  • What is the concerned loop in this case? – Elisha Drion May 1 '18 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.