TeachMeBitcoin

OP_ABS - Absolute Value

From TeachMeBitcoin, the free encyclopedia Reading time: 1 min

4. OP_ABS — Absolute Value

Opcode Reference

Opcode:     OP_ABS
Hex:        0x90
Decimal:    144
Input:      a
Output:     |a|

Overview

OP_ABS pops the top stack element, takes its absolute value (strips the sign), and pushes the result. Both positive and negative inputs yield their magnitude as a positive output. Zero remains zero.

Stack Examples

Input: [7]   → OP_ABS → [7]
Input: [-7]  → OP_ABS → [7]
Input: [0]   → OP_ABS → [0]
Input: [-1]  → OP_ABS → [1]

Bitcoin Core Implementation

case OP_ABS:
{
    if (stack.size() < 1)
        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    CScriptNum bn(stacktop(-1), fRequireMinimal);
    if (bn < bnZero)
        bn = -bn;
    popstack(stack);
    stack.push_back(bn.getvch());
}
break;

Use Cases

OP_ABS is valuable whenever a script needs to enforce a constraint on magnitude regardless of sign. For example, in a script that checks whether a difference between two values is within ±N:

Script pattern (check |a - b| <= 10):
  OP_SUB OP_ABS <10> OP_LESSTHANOREQUAL

This kind of pattern could be used in more complex covenant or channel scripts to verify that some numeric deviation stays within acceptable bounds.

☕ 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!