3

In muldiv, what is this line of code doing?

prod0 |= prod1 * twos

Also can it overflow?

https://github.com/OpenZeppelin/openzeppelin-contracts/blob/f213a10522a7bd808561c5a4b17266065a199dc7/contracts/utils/math/Math.sol#L185

1 Answer 1

2
+50

This is a bitwise operation They do not cause an overflow.

prod0 |= prod1 * twos; translated as prod0 = prod0 | (prod1 * twos);

The | operation is a binary OR. It puts a 1 on the result bit for which at least one of the corresponding operand bits is 1.

0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
1 | 1 = 1

Then if you have incoming values:

prod0 = 2 // 00000010 binary
prod1 = 2
twos = 2 

Then the result prod0 = prod0 | (prod1 * twos) is this:

(prod1 * twos) = 4 // 00000100 binary
prod0 = prod0 | 4 = 00000010 | 00000100 = 000000110 = 6
2
  • 1
    The syntax is clear, but what's the purpose of those instructions inside the multdiv? prod0 and prod1 are the high and low part of the 512 bits product, but what's the purpose of mixing them?
    – Ismael
    Commented Dec 23, 2023 at 22:58
  • 1
    Consider this part in the source code of the entire function. The author comments on everything here: xn--2-umb.com/21/muldiv Commented Dec 24, 2023 at 5:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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