encodeVarint static method
Encodes an integer into a variable-length byte array according to Bitcoin's variable-length integer encoding scheme.
i
The integer to be encoded.
Returns a list of bytes representing the encoded variable-length integer.
If the integer is less than 253, a single byte is used. If the integer is less than 0x10000, a 3-byte encoding is used with the first byte set to 0xfd. If the integer is less than 0x100000000, a 5-byte encoding is used with the first byte set to 0xfe. For integers larger than or equal to 0x100000000, an ArgumentException is thrown since they are not supported in Bitcoin's encoding.
Implementation
static List<int> encodeVarint(int i) {
if (i < 253) {
return [i];
} else if (i < 0x10000) {
final bytes = List<int>.filled(3, 0);
bytes[0] = 0xfd;
writeUint16LE(i, bytes, 1);
return bytes;
} else if (i < 0x100000000) {
final bytes = List<int>.filled(5, 0);
bytes[0] = 0xfe;
writeUint32LE(i, bytes, 1);
return bytes;
} else {
throw ArgumentException("Integer is too large: $i");
}
}