[Ethereum] Convert a number to a 32 bit HEX number using web3

javascriptweb3js

I need to pass the SHA3 function a number, but need it in the format of HEX with the full 32 bits i.e. with leading zeros plus the 0x (e.g. example number 3 ):

web3.sha3("0x0000000000000000000000000000000000000000000000000000000000000003")

Is there a function that takes a number e.g. 3 and creates this string/hex number?

Thanks, Ian

Best Answer

ethereumjs-util has relevant methods: setLengthLeft and bufferToHex:

> const util = require('ethereumjs-util');    
> util.bufferToHex(util.setLengthLeft(123, 2))
'0x007b'
> util.bufferToHex(util.setLengthLeft(3, 32))
'0x0000000000000000000000000000000000000000000000000000000000000003'
Related Topic