Created
July 10, 2022 21:13
-
-
Save PaulRBerg/842cdea29f0f7dbf70ac604107bfd041 to your computer and use it in GitHub Desktop.
Most gas efficient way to check that two integers have the same sign in Solidity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: UNLICENSED | |
pragma solidity >=0.8.15; | |
function checkSameSign(int256 a, int256 b) pure returns (bool sameSign) { | |
// Get the signs of a and b. | |
uint256 sa; | |
uint256 sb; | |
assembly { | |
// This works due to two's complement representation. | |
// "sgt" stamds for "signed greater than". | |
sa := sgt(a, sub(0, 1)) | |
sb := sgt(b, sub(0, 1)) | |
} | |
// If XOR over sa and sb yields 0, a and b are of the same sign. | |
sameSign = sa ^ sb == 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment