TeachMeBitcoin

Script Number Encoding (CScriptNum)

From TeachMeBitcoin, the free encyclopedia Reading time: 1 min

19. Script Number Encoding (CScriptNum)

Overview

All arithmetic opcodes in Bitcoin Script operate on integers encoded in a special format called CScriptNum (named after the C++ class in Bitcoin Core that implements it). Understanding this encoding is essential to correctly reason about any script using arithmetic.

CScriptNum is a little-endian, sign-magnitude variable-length integer encoding. It differs from both standard two's complement (used in most CPUs) and from big-endian encodings.

Encoding Rules

Rule 1: Little-endian byte order
  - Least significant byte comes first

Rule 2: Variable length
  - Use the minimum number of bytes required
  - Leading zero bytes are not allowed (enforced by MINIMALDATA flag)

Rule 3: Sign is encoded in the most significant bit of the LAST byte
  - If the high bit of the last byte is 1, the number is negative
  - If it is 0, the number is positive

Rule 4: Zero is encoded as an empty byte vector
  - [] (empty) = 0
  - Not 0x00 (a single zero byte would be non-minimal)

Encoding Examples

``` Value | Bytes | 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!