Glossary | VarInt

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.


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):



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


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


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.