0

I'm currently working with bytes in Remix. The goal I wanted to achieve was to put variables into bytes in one function, copy bytes, paste bytes to another function as a parameter and unpack these variables and it appears to work.

The following bytes represent these three variables.

12345
"it works"
54321

0x0000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000030390000000000000000000000000000000000000000000000000000000000000008697420776f726b730000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000d431

enter image description here

And a piece of code

function buildBytes(
    uint valA, 
    string calldata strA, 
    uint valB
)
    external view
    returns(bytes memory)
{
    bytes memory strABytes = bytes(strA);
    bytes memory b = new bytes(0);
    b = b.concat(3.toBytes());
    b = b.concat(32.toBytes());
    b = b.concat(valA.toBytes());
    b = b.concat(strABytes.length.toBytes());
    b = b.concat(strABytes);
    b = b.concat(32.toBytes());
    b = b.concat(valB.toBytes());
    return b;
}

function readBytes(bytes calldata pData)
    external view
    returns(
        uint size,
        uint valA,
        string memory str,
        uint valB
    )
{
    uint position = 0;
    size = pData.slice(position, 32).toUint(0);
    position += 32;
    position += 32;
    valA = pData.slice(position, 32).toUint(0);
    position += 32;
    uint length = pData.slice(position, 32).toUint(0);
    position += 32;
    str = string(pData.slice(position, length));
    position += length;
    position += 32;
    valB = pData.slice(position, 32).toUint(0);
}

Now I would like to reproduce this by using web3. My goal is to build bytes via web3 and pass as a parameter in readBytes. I found out I can use web3.utils.toHex. I can make several hex variables I want to pass but I have to merge it to one like the above. The problem is I don't want to add hex, I want to put variables series one by one as hex. How can I do that?

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.