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


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 ):


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))
> util.bufferToHex(util.setLengthLeft(3, 32))
Related Topic