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

web3.sha3("0x0000000000000000000000000000000000000000000000000000000000000003")

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

Thanks, Ian

• Please note, in your question you are asking to format number in full 64 bits, but your actual example has 32 bytes. – max taldykin Feb 28 '17 at 21:26

`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'
``````
• I am facing with `util.setLengthLeft is not a function` error. @max taldykin – alper Dec 26 '17 at 15:48

I see a couple of ways to do this:

## The sprintf way:

How about using https://github.com/alexei/sprintf.js ?

then you could do:

``````var hex = '0x' + sprintf('%064d', 3);
// returns 0x0000000000000000000000000000000000000000000000000000000000000003`
``````

Together with your code:

``````var hex = '0x' + sprintf('%064d', 3);
web3.sha3(hex)
``````

## The pad way:

Alternatively if you are essentially just padding your numbers with zeros, you could extend the `Number` object:

``````Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
``````

Examples:

``````(3).pad();  //returns "03"
``````

Together with your code:

``````var hex = '0x' + (3).pad(64);
web3.sha3(hex)
``````
``````function stringToBytes32(text) {
let result = utils.toUtf8Bytes(text)
if (result.length > 32) { throw new Error('String too long') }
result = utils.hexlify(result);
while (result.length < 66) { result += '0'; }
if (result.length !== 66) { throw new Error("invalid web3 implicit bytes32"); }
return result;
}
``````