Signed greater than comparison using two’s complement representation
This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.
Overview
Opcode:0x13Introduced: Frontier (EVM genesis)SGT performs signed greater than comparison on two 256-bit integers interpreted as two’s complement signed values. Returns 1 if the first value is strictly greater than the second, 0 otherwise. Values are in the range -2^255 to 2^255 - 1.This operation complements SLT for implementing signed conditional logic and range checks.
Specification
Stack Input:
a (top)b
Stack Output:
signed(a) > signed(b) ? 1 : 0
Gas Cost: 3 (GasFastestStep)Operation:
// Interpret as signed two's complementsigned_a = a >= 2^255 ? a - 2^256 : asigned_b = b >= 2^255 ? b - 2^256 : bresult = (signed_a > signed_b) ? 1 : 0
Behavior
SGT pops two values from the stack, interprets them as signed 256-bit two’s complement integers, compares them, and pushes 1 if signed(a) > signed(b), otherwise 0:
// VULNERABLE: Overflow before comparisonint256 result = a - b; // May overflowrequire(result > 0); // Check may be wrong// CORRECT: Check before operationif (a > 0 && b < 0) { require(a <= type(int256).max + b, "overflow");}int256 result = a - b;
// These are equivalent:// a > b === b < aassembly { let greater := sgt(a, b) // Same as: let greater := slt(b, a)}// Choose based on stack layout to minimize swaps
Positive Check Optimization
// Check if value > 0assembly { let isPos := sgt(value, 0) // 3 gas}// Equivalent but more expensive:assembly { let notNeg := iszero(slt(value, 0)) // 6 gas let notZero := iszero(iszero(value)) // 6 gas let isPos := and(notNeg, notZero) // 9 gas total}
Inversion Pattern
// Direct comparison (preferred)assembly { let greater := sgt(a, b) // 3 gas}// Inverted (avoid - more expensive)assembly { let greater := iszero(or(slt(a, b), eq(a, b))) // 12 gas}
Benchmarks
SGT performance matches other comparison operations:Execution time (relative):
SGT: 1.05x (slightly slower due to sign conversion)
SLT: 1.05x
GT/LT/EQ: 1.0x
ISZERO: 0.95x
Gas efficiency:
3 gas per signed comparison
~333,333 comparisons per million gas
Sign conversion adds negligible overhead
References
Yellow Paper - Section 9.1 (Comparison Operations)