I've been looking at the compact representation of integers for integer operations in the Script language. It seems that most operations produce or push byte arrays, but when integer operations are performed those arrays are interpreted using a signed compact format. Is this format actually defined anywhere, or is it strictly bitcoin specific?

As I understand it you can process up to 4 bytes as a integer, the negative of an integer is binary or'd with 0x80. I'm having trouble decoding 1-4 byte negative integers into the correct bit string encoding.

Does anyone have any examples, or can point me in the right direction?


generic big endian MPI format bitcoin-specific little endian format, with implicit size

python implementation


  • This is the right direction. I found the relevant source code in Bitcoind, but I was hoping for a concise explanation of the format if it was documented anywhere outside of code. – Matt Aug 5 '15 at 1:45

CompactSize Unsigned Integers are not used in Script, they are used on the Bitcoin protocol to signify the amount of bytes that the next data structure contains.

You are confusing these with ScriptNumbers, which are interpreted for Arithmetic operations inside of the Script Interpreter.

It should be noted that these actually can be 5 bytes, however if you perform another operation on that 5 byte integer, you will receive an error in the Interpreter.

If you want to see how negative numbers are handled you can look at the implementation of CScriptNum, which the underlying numeric type is a int64_t


I am not sure where you found negative integers. But in most places in bitcoin protocol a compact variable length is used for integers. See reference here https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer

  • The variable length integers are used in the protocol and serialization formats. The compact integer is used in the Script language for representing integer values during operations. So for example, decodescript "4f01e40164" { "asm" : "-1 -100 100", "type" : "nonstandard", "p2sh" : "2N8BQEfUK2Q1e6Svt9ro9LkjVeB5tXQJnBh" } – Matt Jul 3 '15 at 13:40
  • @Matt, Do not mix Variable_length_integer_encoding (the number of inputs/outputs in transaction) and encoding push operations in scripts. These are different things. – amaclin Jul 3 '15 at 14:26
  • I'm not mixing it up, my question is about integer encoding for push operations. – Matt Jul 3 '15 at 14:57
  • 2
    This answer is incorrect. The variable length integers in the P2P protocol are not the same as the integer encoding for numbers inside Script. – Pieter Wuille Aug 2 '15 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.