What is the length of a postcard?

What is the purpose of encoding length?

  • While working with Mikrotik RouterOS API the following requirement caught my attention: "Length of the word should be given as count of bytes that are going to be sent." Source: http://wiki.mikrotik.com/wiki/Manual:API#API_words The above requirement sounds to me as simple as using http://ch2.php.net/strlen. However, the implementation I have found is: /** * @author dapphp/librouteros */ function encodeLength ($length) { if ($length <= 0x7F) { return pack('C', $length); } else if ($length <= 0x3FFF) { return pack('n', ($length | 0x8000)); } else if ($length <= 0x1FFFFF) { $length |= 0xC00000; return pack('C3', ($length >> 16) & 0xFF, ($length >> 8) & 0xFF, ($length & 0xFF)); } else if ($length <= 0xFFFFFFF) { return pack('N', ($length | 0xE0000000)); } else { return pack('CN', 0xF0, $length); } } What is the reason for the above requirement and how to interpret the implementation?

  • Answer:

    It allows packing the "length" variable to less than 4 bytes, presumably to save space. The number of binary "ones" in the result's beginning indicate the value's size. Some examples in binary: 01011010 - The binary starts with a zero, so the value (90) fits to an unsigned byte. 10011011 11001010 - The first bit is a one, followed by a zero. This means the value (7114) fits into two bytes. 11101011 01100001 01111010 11011110 - Three ones in the beginning mean the value (190937822) fits into four bytes. If the value is larger than 0x10000000, it will be packed to five bytes, the first containing binary 11110000 and the rest will be the number as a 32 bit unsigned integer.

Niko Salminen at Quora Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.