TeachMeBitcoin

OP_SUB - Subtracting Two Numbers

From TeachMeBitcoin, the free encyclopedia Reading time: 3 min

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

  1. Pop top → b (subtrahend).

  2. Pop next → a (minuend).

  3. Compute result = a - b.

  4. 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

☕ Help support TeachMeBitcoin

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:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!