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
Int to hex string in javascript - Stack Overflow
JavaScript can't output non-string hex values, can it?
Iterating over a range in hex
Convert from Hex to Decimal
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'
You can use the to string method:
a = 64;
a.toString(16); // prints "40" which is the hex value
a.toString(8); // prints "100" which is the octal value
a.toString(2); // prints "1000000" which is the binary value
Well, it's seems that you want just to concatenate the integer with \x.
If so just to like that:
var number = 62;
var hexStr = '\x' + number.toString(16);
But you have something strange about explaining.
Note: that 62 is not the same as 0x62, 0x62 would be 98.