1

I am currently trying to create an automater for running scripts.

It needs to have two values, lastFromBlock and currentToBlock which need to increment by about 1e5 with each process, so I need to automate the conversion from, say, 7654321 to it's corresponding hex value. I know you can do it with string literals, but I haven't found a tool for integer values.

Tech stack: JS, web3.js

Any ideas?

2 Answers 2

2

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.

0

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.