0

As we know solidity supports only 256-bit big integers. But for crypto primitives (sometimes) we need bigger integers, e.g. 2048-bit.

Question: how can we define 2048-bit integers on a smart contract and perform some modular operations on that size integers?

  • Well, you can use a uint256 array with 8 entries. – goodvibration Nov 15 '18 at 15:51
3

I would try to recreate the operations with an array of uint128. To make it simpler, let's say we want to do it for 512-bit integers:


// With the large number = num[0] + 2^128 * num[1] + 2^256 * num[2] + 2^384 * num[3]
function add(uint128[4] num1, uint128[4] num2) public pure returns(uint128[4] sum) { 
    uint256[4] memory intermediaries;
    intermediaries[0] = (uint256) (num1[0]) + (uint256) (num2[0]);
    intermediaries[1] = (uint256) (num1[1]) + (uint256) (num2[1]);
    intermediaries[2] = (uint256) (num1[2]) + (uint256) (num2[2]);
    intermediaries[3] = (uint256) (num1[3]) + (uint256) (num2[3]);
    uint256 shifter = 2**128;
    uint256 lowerMask = shifter - 1;
    sum[0] = (uint128) (intermediaries[0] & (lowerMask)); // To get the lower part
    sum[1] = (uint128) (intermediaries[1] & (lowerMask) + intermediaries[0] / shifter);
    sum[2] = (uint128) (intermediaries[2] & (lowerMask) + intermediaries[1] / shifter);
    sum[3] = (uint128) (intermediaries[3] & (lowerMask) + intermediaries[2] / shifter);
    // Yes, intermediaries[3] / 2^128 is lost
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.