OP_SUB - Subtracting Two Numbers
2. OP_SUB — Subtracting Two Numbers
Opcode Reference
Opcode: OP_SUB
Hex: 0x94
Decimal: 148
Input: a b
Output: a - b
Overview
OP_SUB subtracts the top stack element from the second-to-top element. Like OP_ADD, it works on CScriptNum-encoded integers. The order of operands is critical: the element pushed last (on top of stack) is the subtrahend, and the element beneath it is the minuend. The result is second - top, or a - b.
How It Works
-
Pop top →
b(subtrahend). -
Pop next →
a(minuend). -
Compute
result = a - b. -
Push result onto the stack.
Stack Visualization
Before OP_SUB:
Stack (top → bottom): [ 3 | 10 | ... ]
(b = 3, a = 10)
After OP_SUB:
Stack (top → bottom): [ 7 | ... ]
(10 - 3 = 7)
Subtraction Producing Negative Results
Bitcoin Script supports negative numbers via CScriptNum's sign-magnitude encoding. This means subtraction can yield a negative value and that value can be pushed back and used further:
Stack before: [ 15 | 5 | ... ] (b=15, a=5)
OP_SUB
Result: 5 - 15 = -10
Stack after: [ -10 | ... ]
The encoding of -10 in CScriptNum is:
Positive 10: 0x0A
Negative 10: 0x8A (high bit set on the last byte signals negative)
Use in Script Logic
A common use pattern for OP_SUB is to verify that the difference between two submitted numbers equals a known constant. This can encode simple puzzle scripts:
Locking script: OP_SUB <5> OP_EQUAL
Unlocking script: <3> <8>
Execution:
Push 3 → [3]
Push 8 → [8, 3]
OP_SUB → [8 - 3] = [5]
Push 5 → [5, 5]
OP_EQUAL → [1] ✓
Another pattern is to verify relative relationships between two witness values — such as confirming that a "new balance" is less than an "old balance" by a specific fee amount.
Bitcoin Core Source Reference
case OP_SUB:
bn = bn1 - bn2;
break;
This is within the same case OP_ADD: case OP_SUB: block shown in the previous section. Bitcoin Core handles both in the same switch statement, differing only in the arithmetic operation.
Important Notes
-
Order matters:
OP_SUBcomputessecond_from_top - top. Reversing the push order changes the sign of the result. -
The result can be negative, which is valid in CScriptNum.
-
Overflow constraints still apply: the result must fit within 4 bytes of CScriptNum encoding.
TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation: