0

I have followed following answer for: Having trouble storing multiple values in a uint256.

For example, I want to pass four uint64 variables merged together as a single argument into smart contract and extract those values.

#python-script:

variable1 = 11;
variable2 = 12;
variable3 = 13;
variable4 = 14;

bits1='{0:064b}'.format(v1)
bits2='{0:064b}'.format(v2)
bits3='{0:064b}'.format(v3)
bits4='{0:064b}'.format(v4)    
mergedVariable = int(bits1 + bits2 + bits3 + bits4, 2)
storagetest8.setCharacter(mergedVariable)
print(storagetest8.getVariables())

contract storagetest8 {

    uint256 variable;

    function setCharacter(uint variable_) 
        external 
    {
        variable = variable_;        
    }


    function getVariables() 
        external view
    returns(uint64 variable1, uint64 variable2, uint64 variable3, uint64 variable4) {
        variable1 = uint64(variable);
        variable = uint64(variable>>64); 
        variable2 = uint64(variable);
        variable = uint64(variable>>64);
        variable3 = uint64(variable);
        variable4 = uint64(variable>>64) // simplified 
    }
}

[Q] Is the approach I implemented in the smart contract correct?

1 Answer 1

3

Your smart contract code is okay, but this is probably simpler:

pragma solidity 0.5.7;

contract Uncombine {
    function getVariables(uint256 combined) external pure returns (uint64 variable1, uint64 variable2, uint64 variable3, uint64 variable4) {
        variable1 = uint64(combined);
        variable2 = uint64(combined >> 64);
        variable3 = uint64(combined >> 128);
        variable4 = uint64(combined >> 192);
    }
}

Not sure what language your combining code is in, but this will do the trick in a language like Python that supports large enough integers:

combined = 11 + (12 << 64) + (13 << 128) + (14 << 192)
5
  • In addition, is it possible to store multiple int64 and uint64 variable under uint256 as well? @smarx
    – alper
    Apr 23, 2019 at 17:49
  • Yes, but the combining will be less straightforward. Since you're using Python, you might want to look at struct.pack.
    – user19510
    Apr 23, 2019 at 17:55
  • Yes, I am using Python as well. Let me investigate if variable1 is -1 as int64 and combine it with other variables reminding as uint64, if possible.
    – alper
    Apr 23, 2019 at 17:57
  • How could I update a single variable; is it possible? For example, I want to update only variable2 with 21? @smarx
    – alper
    Apr 24, 2019 at 16:12
  • 1
    Depends on how you're constructing the combined value. (If you're using addition like in my answer, you could just subtract the old value and add the new one.)
    – user19510
    Apr 24, 2019 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.