Search code examples
ethereumsoliditysmartcontracts

encode three integers into single integer


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?


Solution

  • 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.