FANDOM


Varints, short for variable-sized integers, are used a lot in Monero's core structures. Its format follows.

The high bit of each byte tells you if there's more to be read - if it's set, then there's more bytes. The rest is number data. To convert a varint to an integer type (you should probably check its size, first), simply loop through the bytes, storing all of them with the top bit masked off, and stop when the high bit is clear. Store the last one, and done.

// Decodes varint in RawNum into Out
// Returns size in bytes of varint
// Note that this may not work on big-endian machines
uint64_t FromVarInt(uint64_t *Out, uint8_t *RawNum)
{
int i;
uint8_t tmp[8] = { 0 };

for(i = 0; i < 8 && RawNum[i] & 0x80; ++i)
tmp[i] = RawNum[i] & 0x7F;

tmp[i] = RawNum[i];

*Out = *((uint64_t *)tmp);
return(i + 1);
}