TeachMeBitcoin

OP_NEGATE - Flipping Sign

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

3. OP_NEGATE — Flipping Sign

Opcode Reference

Opcode:     OP_NEGATE
Hex:        0x8F
Decimal:    143
Input:      a
Output:     -a

Overview

OP_NEGATE is a unary opcode that pops the top element off the stack, negates it (flips its sign), and pushes the result back. Positive numbers become negative; negative numbers become positive. Zero remains zero.

How It Works

  1. Pop top element → a.

  2. Compute result = -a.

  3. Push result.

Stack Examples

Input: [7]   → OP_NEGATE → [-7]
Input: [-3]  → OP_NEGATE → [3]
Input: [0]   → OP_NEGATE → [0]

CScriptNum Sign Representation

In CScriptNum, the sign of a number is encoded in the most significant bit of the last byte of the byte array:

+5  = 0x05         (binary: 00000101)
-5  = 0x85         (binary: 10000101, high bit = 1 signals negative)

+127 = 0x7F        (binary: 01111111)
-127 = 0xFF        (binary: 11111111)

+128 = 0x80 0x00   (two bytes needed; high bit of 0x80 would signal negative)
-128 = 0x80 0x80

OP_NEGATE effectively toggles the sign bit in this encoding.

Bitcoin Core Implementation

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

Practical Use

OP_NEGATE is useful when a script needs to convert a value into its inverse for comparison or arithmetic. For instance, to verify that two values are additive inverses of each other (i.e., a + b = 0):

Locking script:   OP_ADD OP_0 OP_EQUAL
Unlocking script: <5> <-5>

OR equivalently:
Locking script:   OP_NEGATE OP_EQUAL
Unlocking script: <5> <5>

Execution of second form:
  Push 5  → [5]
  Push 5  → [5, 5]
  OP_NEGATE → [-5, 5]
  OP_EQUAL  → [1]  ✓ (5 == -(-5)? No... let's rethink)

A cleaner pattern: confirm a provided offset is the negative of a stored constant.

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