Glossary | VarInt
$4,133.51/BTCBuy

VarInt CompactSize

A VarInt (variable integer) is a field used in transaction data to indicate the number of upcoming fields, or the length of an upcoming field.

Example:

Here's a transaction with the VarInt fields highlighted (and if it's referring to a field length, the length of that field is highlighted too):

01000000017b9c26b765a24997e0f855e5d25e86e6816b213e2bbc67bc918df239bfc20158040000006a47304402200aa5891780e216bf1941b502de29890834a2584eb576657e340d1fa95f2c0268022010712e05b30bfa9a9aaa146927fce1819f2ec6d118d25946256770541a8117b6012103d2305c392cbd5ac36b54d3f23f7305ee024e25000f5277a8c065e12df5035926ffffffff028555a700000000001976a914aca504fd373f5f3ba2774a3643d714d6419463bc88ac9bc0ba01000000001976a9143bbebbd7a3414f9e5afebe79b3b408bada63cde288ac00000000

Structure

A VarInt is most commonly a 1 byte hexadecimal value:

                 0x6a = 106 bytes
--|------------------------------------- ... --|
6a47304402200aa5891780e216bf1941b502de29 ... 926

However, if the VarInt is going to be greater than 0xfc (so the number you're trying to express won't fit inside of two hexadecimal characters) then you can expand the field in the following way:

Size Example Description
<= 0xfc 12
<= 0xffff fd1234 Prefix with fd, and the next 2 bytes is the VarInt (in little-endian).
<= 0xffffffff fe12345678 Prefix with fe, and the next 4 bytes is the VarInt (in little-endian).
<= 0xffffffffffffffff ff1234567890abcdef Prefix with ff, and the next 8 bytes is the VarInt (in little-endian).

1 byte = 2 characters

Examples:

1. VarInt = 6a

There is no prefix of fd, fe, or ff, so we know this 1 byte is the VarInt value, and we can convert hexadecimal straight to decimal:

Varint = 6a
       = 106 bytes

hexdec

2. VarInt = fd2602

The prefix is fd, so we know the next 2 bytes (in little-endian) is going to give us the size of the upcoming field:

VarInt = fd2606
       =   2602    (next 2 bytes)
       =   0226    ([swap endian](/tools/swapendian))
       =   550 bytes

Swap Endian

3. Varint = fe703a0f00

Similar to the last example, except fe means it's the next 4 bytes:

VarInt = fe703a0f00
VarInt =   703a0f00
VarInt =   000f3a70
       =   998000 bytes

Why are VarInts used?

In transaction data, fields like the txid and vout have a fixed size, so you always know where they start and end. However, fields like scriptSig can vary in length, so a VarInt field is placed before it so you know how many bytes in length it is.

These VarInts are essential if you have written a script or program that reads transaction data, as without them you wouldn't know where the variable length fields end.

Resources