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:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select: