user116461: In the bitcoin-book, the "Transaction Counter" part of a block is documented as being 1~9 bytes long instead of a fixed size.
How is this counter parsed from the raw data?

user101498: This number is encoded as a variable-length integer, see the txn_count in the block protocol message.
The idea is the following:

Read the first byte as marker
If marker < 0xFD

marker is the number


If marker == 0xFD

read the next 2 bytes as the number


If marker == 0xFE

read the next 4 bytes as the number


If marker == 0xFF

read the next 8 bytes as the number



Or, in Python:
def read_varint(byte_array):
    marker = byte_array[0]
    if marker < 0xfd:
        return marker
    elif marker == 0xfd:
        return int.from_bytes(byte_array[1:3], 'little')
    elif marker == 0xfe:
        return int.from_bytes(byte_array[1:5], 'little')
    else:
        return int.from_bytes(byte_array[1:9], 'little')

See also the implementation in Bitcoin Core here.

116461: <p>In the <a href="https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch09.asciidoc#structure-of-a-block" rel="nofollow noreferrer">bitcoin-book</a>, the &quot;Transaction Counter&quot; part of a block is documented as being 1~9 bytes long instead of a fixed size.</p>
<p>How is this counter parsed from the raw data?</p>
 101498: <p>This number is encoded as a <a href="https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer" rel="nofollow noreferrer">variable-length integer</a>, see the <code>txn_count</code> in the <a href="https://en.bitcoin.it/wiki/Protocol_documentation#block" rel="nofollow noreferrer">block protocol message</a>.</p>
<p>The idea is the following:</p>
<ul>
<li>Read the first byte as <code>marker</code></li>
<li>If <code>marker &lt; 0xFD</code>
<ul>
<li><code>marker</code> is the number</li>
</ul>
</li>
<li>If <code>marker == 0xFD</code>
<ul>
<li>read the next 2 bytes as the number</li>
</ul>
</li>
<li>If <code>marker == 0xFE</code>
<ul>
<li>read the next 4 bytes as the number</li>
</ul>
</li>
<li>If <code>marker == 0xFF</code>
<ul>
<li>read the next 8 bytes as the number</li>
</ul>
</li>
</ul>
<p>Or, in Python:</p>
<pre><code>def read_varint(byte_array):
    marker = byte_array[0]
    if marker &lt; 0xfd:
        return marker
    elif marker == 0xfd:
        return int.from_bytes(byte_array[1:3], 'little')
    elif marker == 0xfe:
        return int.from_bytes(byte_array[1:5], 'little')
    else:
        return int.from_bytes(byte_array[1:9], 'little')
</code></pre>
<p>See also the implementation in Bitcoin Core <a href="https://github.com/bitcoin/bitcoin/blob/5ba5becbb5d8c794efe579caeea7eea64f895a13/src/serialize.h#L350-L450" rel="nofollow noreferrer">here</a>.</p>
