0
1
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:
- What is the significance of that size of the array?
- Why the bitwise operations?
- Why write the array to the stream in reverse order?
I am not familiar with this, so I won't post a full answer, but it makes sense to think about this from a binary perspective. Decimal won't help you much.
1) The size of the array makes a jump after each (8*i) bits. 2) (n & 0x7F) grabs the last 7 bits of N. The (len ? 0x80 : 0x00) makes it add an extra 1 unless it's the first run. This explains the above - extra bits. 3) If (n <= 0x7F) tells you there are no bits beyond the ones seen, so no need to continue. 4) The array is written to in reverse order - it is then written to the stream backwards so that it is in the correct order again. – Jake – 2017-07-14T16:11:29.397
I should clarify. The array isn't written to in reverse order, per se. But you're taking the least significant bits out of
nand putting them intotmpin a forwards order. Writing it backwards to the stream means the most significant bits hit the stream first. – Jake – 2017-07-14T16:14:54.787@JArkinstall, this makes a ton of sense grabbing the last 7 bits, especially considering David Schwartz's answer. This is how they generate the variable length data. Thanks! – InfinityCounter – 2017-07-14T16:30:39.870