shuijian-xu / bitcoin

0 stars 0 forks source link

varint? #156

Open shuijian-xu opened 4 years ago

shuijian-xu commented 4 years ago

A single byte has 8 bits, so anything over 255 inputs will not be expressible in a single byte. This is where varints come in

shuijian-xu commented 4 years ago

Varint is shorthand for variable integer, which is a way to encode an integer into bytes that range from 0 to 264 – 1. We could, of course, always reserve 8 bytes for the number of inputs, but that would be a lot of wasted space if we expect the number of inputs to be relatively small (say, under 200). This is the case with the number of inputs in a normal transaction, so using varints helps to save space.

shuijian-xu commented 4 years ago

Varint is shorthand for variable integer, which is a way to encode an integer into bytes that range from 0 to 264 – 1. We could, of course, always reserve 8 bytes for the number of inputs, but that would be a lot of wasted space if we expect the number of inputs to be relatively small (say, under 200). This is the case with the number of inputs in a normal transaction, so using varints helps to save space.

shuijian-xu commented 4 years ago

Varint is shorthand for variable integer, which is a way to encode an integer into bytes that range from 0 to 2^64 – 1.

We could, of course, always reserve 8 bytes for the number of inputs, but that would be a lot of wasted space if we expect the number of inputs to be relatively small (say, under 200).

This is the case with the number of inputs in a normal transaction, so using varints helps to save space.

shuijian-xu commented 4 years ago

Varint is shorthand for variable integer, which is a way to encode an integer into bytes that range from 0 to 2^64 – 1.

We could, of course, always reserve 8 bytes for the number of inputs, but that would be a lot of wasted space if we expect the number of inputs to be relatively small (say, under 200).

This is the case with the number of inputs in a normal transaction, so using varints helps to save space.

shuijian-xu commented 4 years ago

Variable integers work by these rules:

  1. If the number is below 253, encode that number as a single byte (e.g., 100 → 0x64).

  2. If the number is between 253 and 2^16 – 1, start with the 253 byte (fd) and then encode the number in 2 bytes in little-endian (e.g., 255 → 0xfdff00, 555 → 0xfd2b02).

  3. If the number is between 2^16 and 2^32 – 1, start with the 254 byte (fe) and then encode the number in 4 bytes in little-endian (e.g., 70015 → 0xfe7f110100).

  4. If the number is between 2^32 and 2^64 – 1, start with the 255 byte (ff) and then encode the number in 8 bytes in little-endian (e.g., 18005558675309 → 0xff6dc7ed3e60100000).