How to convert decimal numbers to hexadecimals strings using web3.js and ethers.js
How to convert decimal numbers to hexadecimals strings using web3.js and ethers.js
Hexadecimal strings are used to represent addresses and encode gas data and values. These scripts show you how to do it programmatically within your DApps.
const Web3 = require("web3");
function decimalToHexadecimal(decimalNumber) {
return Web3.utils.toHex(decimalNumber);
}
// Run the function and log the result
const decimalNumber = 255;
const hexadecimalNumber = decimalToHexadecimal(decimalNumber);
console.log(
`The hexadecimal representation of ${decimalNumber} is ${hexadecimalNumber}`
);
The hexadecimal representation of 255 is 0xff
Converting decimal to hexadecimal is a standard operation in Web3; let’s see how to do it using two of the popular JavaScript libraries:
- web3.js
- ethers.js (V6)
Install node.js in case it is not installed yet.
Create a new directory for your project, then install the web3.js and ethers.js libraries:
npm install web3 ethers
The web3.js library uses the utils.toHex()
function to take care of this operation, while ethers V6 uses the toBeHex()
function.
The scripts show how to use those functions and log the result.
return Web3.utils.toHex(decimalNumber);
Now you can run the scripts from the terminal and see the results displayed.
node YOUR_SCRIPTS_NAME
const Web3 = require("web3");
function decimalToHexadecimal(decimalNumber) {
return Web3.utils.toHex(decimalNumber);
}
// Run the function and log the result
const decimalNumber = 255;
const hexadecimalNumber = decimalToHexadecimal(decimalNumber);
console.log(
`The hexadecimal representation of ${decimalNumber} is ${hexadecimalNumber}`
);
The hexadecimal representation of 255 is 0xff
const Web3 = require("web3");
function decimalToHexadecimal(decimalNumber) {
return Web3.utils.toHex(decimalNumber);
}
// Run the function and log the result
const decimalNumber = 255;
const hexadecimalNumber = decimalToHexadecimal(decimalNumber);
console.log(
`The hexadecimal representation of ${decimalNumber} is ${hexadecimalNumber}`
);
The hexadecimal representation of 255 is 0xff