1

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

1 Answers1

2

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)))
    }
Sep Roland
  • 33,889
  • 7
  • 43
  • 76
  • Hey that 2nd bit there works perfectly! thank you! I'm still new at Solidity and just started learning assembly code today. I would upvote but no rep yet :) – Taylor Lepper Nov 13 '22 at 04:19
  • @TaylorLepper: You can't upvote without rep, but you can still "accept" an answer (checkmark under the vote arrows), if it fully solves your problem. That gives more rep than an upvote, and lets future readers know that the answer worked for you. – Peter Cordes Nov 13 '22 at 06:13