Module 02
Arithmetic
Bitcoin Script can do basic math on stack items — addition, subtraction, comparison, and more. The inputs and outputs are all CScriptNum: a compact variable-length integer encoding specific to Bitcoin.
What you'll learn
- →Decode and encode CScriptNum integers
- →Apply OP_ADD, OP_SUB, OP_ABS, OP_NEGATE, OP_MIN, OP_MAX
- →Use OP_WITHIN to perform range checks
- →Understand why Script integers are limited to 4 bytes
01
Add and subtract
OP_ADD pops the top two items, adds them, and pushes the result. OP_SUB subtracts the top from the second-to-top (second − top). Both opcodes consume their inputs — nothing is preserved.
OP_ADDPops two items, pushes their sum. Here 3 + 4 = 7.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_SUBPops two items, pushes second − top. Here 9 − 4 = 5.
↑ top of stack
nothing here yet
press Step or Run to push an item
ScriptNumError. All arithmetic operands use CScriptNum encoding.Why 4-byte integers?
02
Shortcuts and signs
Several opcodes modify the top item in-place without needing a second operand.
OP_1ADDAdds 1 to the top item. Cheaper than pushing OP_1 and calling OP_ADD.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_1SUBSubtracts 1 from the top item.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_NEGATEFlips the sign. Positive becomes negative and vice versa.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_ABSReturns the absolute value. Negative numbers become positive.
↑ top of stack
nothing here yet
press Step or Run to push an item
03
Range operations
OP_MIN and OP_MAX return the smaller or larger of two values. OP_WITHIN checks whether a value falls in the range [min, max).
OP_MINPops two items, pushes the smaller. Here min(3, 7) = 3.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_MAXPops two items, pushes the larger. Here max(3, 7) = 7.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_WITHINPushes 1 if value is in [min, max), else 0. Stack order: value, min, max. Here 1 ≤ 5 < 10 → true.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_10 OP_1 OP_10 OP_WITHIN return? The upper bound is exclusive.Ctrl+Enter to run
↑ top of stack
nothing here yet
press Step or Run to push an item
04
Your turn
Use arithmetic to hit a specific target.
Leave 21 on the stack
Ctrl+Enter to check