将三个整数编码为单个整数

encode three integers into single integer

我必须将 3 个数字编码成同一个整数。

我有这 3 个测量结果

uint256 carLength;
uint256 carWidth;
uint256 carDepth;

并且我想将这 3 个数字编码为同一个整数,以便解码。我的问题是我在这个低级别上不是很有经验。

我想像这样的功能

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

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

关于如何进行的建议?

如果您将每个 a,b,c 设为 32 位(4 字节,或大多数语言中的标准 int),您可以通过一些简单的位移来实现。

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


}

编码时,我们只需将数字移动到连续的 32 位部分。解码时,我们做相反的事情。但是,对于b和c,我们需要先左移,再右移,先消去其他数字。

uint256,顾名思义,实际上有 256 位,因此如果确实需要,您实际上可以在其中放入 3 个数字,每个数字最多 85 位。