Loading...
Hello Folks,
So in this session we will be discussing about converting a negative number to two's compliment using web3 from nodejs.
To do that we need to have web3 Node module installed on our system.
We can do this by running the following code on the cmd
npm install web3
Then let's run our node server. Just run the following code on cmd.
node
Then we need web3 module in our server so run the following code
var Web3 = require('web3')
we will be needing a Blockchain network to create an account so get an rpc url from here
Just click on the link -> Login to your account ->Click on ethereum on left side bar ->create project ->settings->keys->endpoints
and choose your respective testnet rpc url
rpc url it will look like this - https://kovan.infura.io/v3/your_api_key
var url = 'your RPC url here'
Then run this one
var web3 = new Web3(url)
To convert a negative numer into a two’s complement; we can use this utility function
Basic Syntax:
web3.utils.toTwosComplement(number)
This will return the converted hex string value
Example:
web3.utils.toTwosComplement('-1');
> "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" //output
web3.utils.toTwosComplement(-1);
> "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" //output
web3.utils.toTwosComplement('0x1');
> "0x0000000000000000000000000000000000000000000000000000000000000001" //output
web3.utils.toTwosComplement(-15);
> "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1" //output
web3.utils.toTwosComplement('-0x1');
> "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" //output
So that's all for today's session.
For test ethers and link tokens. Click Here
For many more exciting tutorials keep following my username @BlockTalks_Raj
!!!!!HAPPY LEARNING!!!!