Encoding integers in solidity

0 votes
I have 3 integers of uint256 type in my solidity code. Now I want encode these 3 integers into one single integer. How can I do it?
Aug 13, 2018 in Blockchain by slayer
• 29,050 points
37 views

1 answer to this question.

0 votes

There are different ways to do this but I am going to share the method that I use.

The method I use to encode is bitshifting. What you have to do is, to encode, you have to move the numbers into sequential 32-bit section. And to decode the integer, you do the opposite. I am also sharing the code I use:

pragma solidity 0.4.24;


contract Test {

    function encodeNumbers(uint256 a, uint256 b, uint256 c) public view returns(uint256 encoded) {

        encoded |= (a << 64);

        encoded |= (b << 32);

        encoded |= (c);

        return encoded;

    }


    function decodeNumber(uint256 encoded) public view returns (uint256 a, uint256 b, uint256 c) {

        a = encoded >> 64;

        b = (encoded << 192) >> 224;

        c = (encoded << 224) >> 224;

        return;

    }

}
answered Aug 13, 2018 by digger
• 27,620 points

Related Questions In Blockchain

+1 vote
1 answer

What is the difference between if() and require() statement in solidity??

If() and require() have separate functions and ...READ MORE

answered Apr 18, 2018 in Blockchain by Shashank
• 10,330 points
301 views
+1 vote
1 answer

what is use of msg.sender in solidity code?

msg.sender(address) function indicated the sender of the ...READ MORE

answered Apr 24, 2018 in Blockchain by Shashank
• 10,330 points
309 views
+1 vote
2 answers

How to convert INT to STRING in Solidity?

Look at the following code : function uintToString(uint ...READ MORE

answered Jun 27, 2018 in Blockchain by Christine
• 15,790 points
769 views
0 votes
1 answer

Should I require a specific condition when working with indexes in Solidity?

You are using it correctly. require is intended to ...READ MORE

answered Jul 17, 2018 in Blockchain by ariaholic
• 7,320 points
22 views
0 votes
1 answer

Truffle tests not running after truffle init

This was a bug. They've fixed it. ...READ MORE

answered Sep 11, 2018 in Blockchain by Christine
• 15,790 points
105 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to get all address and send ethers in solidity using a loop?

I found a similar code somewhere: contract  Holders{ uint ...READ MORE

answered Jul 31, 2018 in Blockchain by digger
• 27,620 points
125 views
0 votes
1 answer

What does _ mean in solidity language?

The _ symbol is a place holder. ...READ MORE

answered Aug 10, 2018 in Blockchain by digger
• 27,620 points
26 views