Integer encodings

General considerations

  basics

The transaction data in the example is displayed as one long hexadecimal string. This means that every byte is encoded by two digits ranging from 0 to f.

When parsing a transaction their are always three possibilities for the next field:

The integers with a fixed width are always using 4 bytes. The byte array representing a script has its own encoding rules described here.

Fixed-width integers

  UInt32

The fixed-width integers used in transactions (not in scripts) are always encoded as unsigned little-endian integers using 4 bytes, i.e. 32 bits (UInt32). Due to their little-endian flavour they start with the least significant byte.

Convert hex number to decimal

Decimal number

Variable length integers

  VarInt

The VarInt used by bitcoin is an unsigned integer encoding based on a variable number of bytes. It uses between 1 and 9 bytes depending on the size of the integer and is able to encode values between 0 and 264-1. The decoding of a VarInt from a transaction works as follows:

Parse the first byte of the VarInt as a UInt8 and determine the length of the integer based on the value.

Convert VarInt hex number to decimal

Decimal number