Been reading the bitcoin source code but unsure what this segment of Serialize.h does I decided to learn about crypto (and C++) by first reading the entire C++ implementation of bitcoin. I'm having issue with this segment of serialize.h

template&lt;typename Stream, typename I&gt;
void WriteVarInt(Stream&amp; os, I n)
{
    unsigned char tmp[(sizeof(n)*8+6)/7];
    int len=0;
    while(true) {
        tmp[len] = (n &amp; 0x7F) | (len ? 0x80 : 0x00);
        if (n &lt;= 0x7F)
            break;
        n = (n &gt;&gt; 7) - 1;
        len++;
    }
    do {
        ser_writedata8(os, tmp[len]);
    } while(len--);
}


I get that it is writing some variable to a stream, however I don't understand the significance of

(sizeof(n)*8+6)/7


for the array size. Then it enters some loop where it performs a bitwise or of the bitwise and of the loop counter and the hex representation of 127, and either the hex of 128 or 0 depending on whether or not the loop counter is 0.

Then if the number is less than 127 it is going to exit and write the reverse of the array to the stream.

What I don't understand is:


What is the significance of that size of the array?
Why the bitwise operations?
Why write the array to the stream in reverse order?
The encoding used fits 7 bits of data in each byte of output. So, to figure out the number of bytes of output you will produce, you need to take the number of bits of input and divide by 7 (since 7 bits of input fit in each byte of output), rounding up.

So, sizeof(n) is the number of bytes of output. Multiplying by 8 gives the number of bits of input. We divide by 7 to get the number of bytes of output needed to fit that many bits of input.

But integer division rounds down. To divide by 7 but round up, we add 6 to the number before dividing. That makes it round up.