encode three integers into single integer

非 Y 不嫁゛ 提交于 2021-02-10 09:40:07

问题


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?


回答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.



来源:https://stackoverflow.com/questions/51770787/encode-three-integers-into-single-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!