Skip to content

Instantly share code, notes, and snippets.

@PaulRBerg
Created July 10, 2022 21:13
Show Gist options
  • Save PaulRBerg/842cdea29f0f7dbf70ac604107bfd041 to your computer and use it in GitHub Desktop.
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
// 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