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.
Overview
Overview
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)
Environment setup
Environment setup
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
Function to convert decimal to hex
Function to convert decimal to hex
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.
Run the script
Run the script
Now you can run the scripts from the terminal and see the results displayed.
node YOUR_SCRIPTS_NAME