# How to calculate variable length fields?

Some parts of bitcoin tx Ex: Script are of variable length var_int. Can someone explain how to calculate its value from that var_int table.

Ex: In the below tx, the bolded part is script-length. its length is supposed to be 349 bytes. When I convert `fd5d01` directly to decimal, its value is 16604417. I think I didn't understand var_int table correctly.

Can someone explain me the rules from that table?

it's a lot easier, just omit the "fd". Here is the explanation from the bitcoin developers webpages.

Assuming you have the value in an array (tx_array) and a pointer into the array (tx_array_ptr), here is an (unixoide shell script) code example:

``````# var_int is defined as:
# value         size Format
# < 0xfd        1    uint8_t
# <= 0xffff     3    0xfd + uint16_t
# <= 0xffffffff 5    0xfe + uint32_t
# -             9    0xff + uint64_t
# if value <= 0xfd, Bytes  = 1
# if value =  0xfd, Bytes  = 2
# if value =  0xfe, Bytes  = 4
# if value =  0xff, Bytes  = 8
var_int=\${tx_array[\$tx_array_ptr]}
if [ "\$var_int" == "FD" ] ; then
tx_array_ptr=\$(( \$tx_array_ptr + 1 ))
tx_array_bytes=2
var_int=\$( get_TX_section )
elif [ "\$var_int" == "FE" ] ; then
tx_array_ptr=\$(( \$tx_array_ptr + 1 ))
tx_array_bytes=4
var_int=\$( get_TX_section )
elif [ "\$var_int" == "FF" ] ; then
tx_array_ptr=\$(( \$tx_array_ptr + 1 ))
tx_array_bytes=8
else
var_int=\${tx_array[\$tx_array_ptr]}
fi
``````

When you have your var_int, don't forget reversing the hex values (big endian conversion)! Then you can send the value e.g. to your decimal converter, so for your value (fd5d01) you get:

1. omit the "fd"
2. take the next two bytes "5d01"
3. big endian conversion "015d"
4. convert to decimal:

use of "bc" to convert value to decimal:

``````\$ echo "ibase=16;015D" | bc
349
``````