将三个整数编码为一个整数 [英] encode three integers into single integer

查看:86
本文介绍了将三个整数编码为一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将3个数字编码为相同的整数.

I have to encode 3 numbers into the same integer.

我有这3个测量值

uint256 carLength;
uint256 carWidth;
uint256 carDepth;

,我想将这3个数字编码为相同的整数,并且可以解码.我的问题是我在这个低水平上经验不足.

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.

我考虑这样的功能

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)您可以通过一些简单的移位来做到这一点.

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.

这篇关于将三个整数编码为一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆