Home > Mobile >  Greatest of 4 Numbers Solidity Assembly Code
Greatest of 4 Numbers Solidity Assembly Code

Time:11-15

I'm trying to create a function to find the greatest of the 4 numbers input as parameters.

Using solidity assembly code.

I've made a successful greatest of 2 numbers already, but can't seem to figure this one out.

Heres my code it just returns 0 every time

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.4.26;

contract LargestOfFourNums {
    function largestOfFour(
        uint256 num1,
        uint256 num2,
        uint256 num3,
        uint256 num4
    ) public view returns (uint256 result) {

        assembly {
            let winnerA := gt(num1, num2)
            let winnerB := gt(num3, num4)
    

            jumpi(num1Greater, gt(winnerA, winnerB))
            jump(num2Greater)

        num1Greater:
            result := winnerA
            jump(end)
        num2Greater:
            result := winnerB
        end:
        }
    }
}

I've tried using mstore(0x80, winnerA)

But that didn't seem to change anything.

I even tried sload(0x80) as well as sload(winnerA) to try and call it later

CodePudding user response:

Why the extra jumping? jump(num2Greater) is redundant anyway. You could have the code 'fall through' in one of the cases.

You can use next method to obtain the maximum and minimum of two 32-bit integers:

c = a - b
k = (c >> 31) & 1
max = a - k * c
min = b   k * c

This allows for a branchless solution:

assembly {
    let maxA := sub(num1, mul(lt(num1, num2), sub(num1, num2)))
    let maxB := sub(num3, mul(lt(num3, num4), sub(num3, num4)))
    result   := sub(maxA, mul(lt(maxA, maxB), sub(maxA, maxB)))
    }
  • Related