2

I have to encode 3 numbers into the same integer.

I have these 3 measurements

uint256 carLength;
uint256 carWidth;
uint256 carDepth;

and i want to encode these 3 numbers into the same integer with the possibility to decode. My problem is that I'm not very experienced at this low level.

i think about functions like this

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

function decodeNumber(uint256) public view returns (uint256, uint256, uint256);

advice on how to proceed?

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
Diagonal Think
  • 323
  • 1
  • 3
  • 14
  • Why do you want to combine the three integers into one? Is it to save space and the related gas costs of `SSTORE`? – carver Aug 09 '18 at 21:15

1 Answers1

1

If you take each of a,b,c to be 32 bits (4 bytes, or a standard int in most languages) you can do it with some simple bitshifting.

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;
    }


}

When encoding, we simply move the numbers into sequential 32-bit sections. When decoding, we do the opposite. However, in the case of b and c, we need to first blank out the other numbers by shifting left first, then shifting right.

uint256, as the name says, actually has 256 bits, so you could actually fit 3 numbers up to 85 bits each in there, if you really needed to.

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
  • this is valid also with negative numbers? im trying but seems not work – Diagonal Think Aug 09 '18 at 19:09
  • uint256 is unsigned, it has no negative numbers – Raghav Sood Aug 09 '18 at 19:13
  • 1
    You will need to use int256 if you want negative numbers, but the conversion is a bit different since you need to sign extend. There are plenty of C/C++ examples of handling that on Google and Stack Overflow, the same concept applies here – Raghav Sood Aug 09 '18 at 19:14
  • 2
    If the goal is just to reduce gas costs when storing the values, you can just put them in a `struct` and let the Solidity compiler do the work, e.g. `struct foo { uint8 a; uint8 b; uint8 c; }`. – user94559 Aug 09 '18 at 22:33
  • @RaghavSood Thanks for sharing amazing input. Could you please point out some resources that I can follow for negative numbers? I will really appreciate it. – Justin Pham Aug 26 '21 at 23:18