Packing Variables Manually

Published by Mario Oettler on

Last Updated on 24. March 2025 by Mario Oettler

In the previous topic, the EVM took care of storing and retrieving the values of two or more variables from a single slot. But it is also possible to do this manually by bit shifting.

Let us have a look at an example.

Example

pragma solidity 0.8.29;

contract PackManually{
    uint64 public varA;


    function setVariables() public{
        // This stores two values 1 and 2 in a single 64 bit variable
        varA = uint64(1) << 32 | uint64(2);
    }

    function readVariables() public returns(uint32, uint32){
        uint32 a = uint32(varA >> 32);
        uint32 b = uint32(varA);
        return (a, b);
    }

}

For comparison, we use the following contract where EVM packing is used.

pragma solidity 0.8.21;

contract PackManualla_Unpacked{
    uint32 public varA;
    uint32 public varB;

    function setVariables() public{
        // This stores two values 1 and 2 in a single 64 bit variable
        varA = 1;
        varB = 2;
    }

    function readVariables() public returns(uint32, uint32){
        return (varA, varB);
    }

}

The gas costs are as follows:

DeploymentFirst value assignmentSecond value assignmentRead variables
Unpacked180020502182733327414
Packed179827498782699327402

The downside on this approach is that it compromises readability and increases complexity.

Categories: