How does the variable length integer work?

4

4

I'm trying to write a script that constructs a serialized bitcoin transaction from scratch.

But when it comes to the number of inputs, the field is a variable length integer.

It's typically only 1 byte (2 characters) in length and you do not have to do anything with it, because bitcoin transactions rarely have more than 0xFE (253) inputs.

But what happens when there are more than 253 inputs and the size of the field has to increase to accommodate it?

How would you put a count of 256 inputs in to this field?

https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer

inersha

Posted 2015-09-08T18:15:09.137

Reputation: 2 236

Answers

11

From the Bitcoin forum:

The way the variable length integer works is:

  • Look at the first byte
  • If that first byte is less than 253, use the byte literally
  • If that first byte is 253, read the next two bytes as a little endian 16-bit number (total bytes read = 3)
  • If that first byte is 254, read the next four bytes as a little endian 32-bit number (total bytes read = 5)
  • If that first byte is 255, read the next eight bytes as a little endian 64-bit number (total bytes read = 9)

Sam Jones

Posted 2015-09-08T18:15:09.137

Reputation: 151

2

How would you put a count of 256 inputs in to this field?

FD 00 01

(00 01) is low-endian representation of decimal(256)

amaclin

Posted 2015-09-08T18:15:09.137

Reputation: 5 763

Thanks. So all values above 0xFD are little-endian? Also, would decimal(65536) be FE 00 00 01?inersha 2015-09-09T09:17:13.593

no. (FE 00 00 01 00) because FE is prefix for 32-bit low-endianamaclin 2015-09-11T19:24:43.110