Script Number Encoding (CScriptNum)
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
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: