Convert a number to a hexadecimal string with:
hexString = yourNumber.toString(16);
And reverse the process with:
yourNumber = parseInt(hexString, 16);
Answer from Prestaul on Stack OverflowConvert a number to a hexadecimal string with:
hexString = yourNumber.toString(16);
And reverse the process with:
yourNumber = parseInt(hexString, 16);
If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function toString(16) will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.
function decimalToHexString(number)
{
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}
return number.toString(16).toUpperCase();
}
console.log(decimalToHexString(27));
console.log(decimalToHexString(48.6));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
solidity - How do you change an integer to a hex in javascript / web3.js? - Ethereum Stack Exchange
Iterating over a range in hex
Is there a way to modify HEX color codes in CSS?
Is it possible to programmatically calculate a hex color based on another hex color?
To convert an integer to a hexadecimal value in JavaScript, you can use the Number.toString() method and specify a radix of 16 (hexadecimal) as the second argument. For example, to convert the integer 7654321 to a hexadecimal value, you could use the following code:
const intValue = 7654321;
const hexValue = intValue.toString(16);
console.log(hexValue); // Output: "b1bcd1"
In Web3.js, you can use the web3.utils.toHex() method to convert an integer to a hexadecimal value. This method takes the integer value as the first argument and an optional second argument that specifies the number of characters in the resulting hexadecimal value. For example, to convert the integer 7654321 to a hexadecimal value with 8 characters, you could use the following code:
const intValue = 7654321;
const hexValue = web3.utils.toHex(intValue, 8);
console.log(hexValue); // Output: "00000b1bcd1"
You can then use the hexValue variable in your automation script as needed.
Found the answer in another thread:
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'