Skip to main content
edited title
Link

Been reading the bitcoin source code but unsure what this segment of Serialize.h does

Source Link

Been reading the bitcoin source code but unsure what this segment of Serialize.h

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<typename Stream, typename I>
void WriteVarInt(Stream& os, I n)
{
    unsigned char tmp[(sizeof(n)*8+6)/7];
    int len=0;
    while(true) {
        tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
        if (n <= 0x7F)
            break;
        n = (n >> 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:

  1. What is the significance of that size of the array?
  2. Why the bitwise operations?
  3. Why write the array to the stream in reverse order?