且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-09 17:25:27

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

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


}

编码时,我们只需将数字移动到连续的32位部分中.解码时,我们做相反的事情.但是,对于b和c,我们需要先清除其他数字,方法是先左移然后右移.

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 实际上具有256位,因此,如果您确实需要的话,实际上可以在其中容纳3个数字,每个数字最多为85位.

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.