I have a function from a library:

    function sliceUint(bytes bs, uint start)
        internal pure
        returns (uint)
        require(bs.length >= start + 32, "slicing out of range");
        uint x;
        assembly {
            x := mload(add(bs, add(0x20, start)))
        return x;

the purpose of which is it takes bytes-encoded parameter and converts it to a uint. The reason I need this is because I need to interact with a contract function that has a bytes calldata _extra parameter that will call back to my contract with. I need to pass in a uint256 in the initial call, then decode with sliceuint on the callback so I can recover it.

If I understand the assembly right, it's loading into x, from the bytes bs variable, but from an offset of 0x20+start.

My question is:

  1. How do I convert from a uint256 to bytes in Solidity to feed to the function?
  2. How do I convert from a uint256 to bytes in Web3.js for same?

In web3.js I have tried:

web3.eth.abi.encodeParameter('bytes', 1337)

and passed that to the bytes parameter of my function. It usually reverts with an error that I may have tried to access an array out of bounds or didn't provide enough gas (I provided enough gas.)

If I try to follow what the sliceUint function does, it seems like it's pulling from the wrong place (0x80 looks like the right place) so what am I doing wrong am I encoding wrong, calling sliceUint wrong?

  • I made sliceUint public and tried await tester.sliceUint(web3.eth.abi.encodeParameter('uint256', 1337), 0) and this seems to convert correctly. Still errors out when I pass the bytes through the contract.
    – Dobit
    Jul 26, 2021 at 15:05

1 Answer 1


If you want to encode 1234 to a bytes array from web3 you can combine toHex and padLeft from web3.utils.

> web3.utils.padLeft(web3.utils.toHex(1234), 64)


To decode from solidity call sliceUint with start = 0

bytes memory a = hex"00000000000000000000000000000000000000000000000000000000000004d2";
uint256 x = sliceUint(a, 0);

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.