I'm trying to send 12 integer as bytes to a contract function. If I use


the variable will become 0xc

The problem is that when contract function parses bytes, it reads uint256, so the result is revert.

How can I generate a hex with specific length? Like uint256, 128, 64, 32?

Edit: just tested manually and the variable I need is 0x000000000000000000000000000000000000000000000000000000000000000c There must be a way to generate it somehow.

  • 1
    What do you want in the bytes? Do you want the ascii string "12"? If yes, then use web3.utils.asciiToHex("12"). Commented Sep 2, 2019 at 11:49
  • My goal is to pass integer 12 as an uint256 hex. toHex returns 0xc, but I want something like 0x000000000000000000000000000000000000000000000000000000000000000c - not sure if I put correct number of zeros, but passing this variable manually gave me correct result. And no, asciiToHex also didn't work, I need to pass integer, not string.
    – Radek_pl
    Commented Sep 2, 2019 at 12:06
  • If your function takes uint256, then you can just pass 12. No need for any web3.utils function. Commented Sep 2, 2019 at 12:10
  • My function takes bytes.
    – Radek_pl
    Commented Sep 2, 2019 at 12:11
  • So how exactly would "0x000000000000000000000000000000000000000000000000000000000000000c" help you here? If anything, you need the zeros at the end, not at the beginning (assuming you want to compare it to a string or something like that). Commented Sep 2, 2019 at 12:24

1 Answer 1


simple you use padLeft. So first you turn your hex into string then pad the length that you want ( for example uint256 is 32 bytes so you need to pad 64 characters). Then from that string you convert it back to hex

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.