assoonaspossible
assoonaspossible

Reputation: 25

How to decode packet length from variable number of bytes?

I am intercepting data from one application, it accepts binary data in the form of packets of information. At the beginning of each packet, depending on the length of the packet, there are 1, 2 or 3 bytes containing the length of the packet. But the length is encoded, as for a short packet it is 1 byte stating, for longer ones 2 or 3 bytes. The packet length also includes the number of bytes in which the length is encoded

Example packets:

  1. 1a0420ee26ee2622..., actual packet length is 23 bytes, 0x1A - is packet length
  2. 2e0220b8218fbd07..., actual packet length 43 bytes, 0x2E - is packet length
  3. ac060014ec0f9700..., actual packet length 810 bytes, 0xAC06 - is packet length
  4. af0c0014ca4f9702..., actual packet length 1581 bytes, 0xAF0C - is packet length
  5. eb080014a46f9700..., actual packet length 2399 bytes, 0xEB08 - is packet length
  6. ff08021734c52b00..., actual packet length 2796 bytes, 0xFF08 or 0xFF0802 - is packet length

During my brainstorming I was able to determine that for packets 1 and 2 the length is obtained

byteArr[0] - 3

// For 1a0420ee26ee2622... it's 1a => 26 - 3 = 23 bytes

for 3 and 4 the length is obtained by the formula

(byteArr[1] << 7) + (byteArr[0] & 127) - 2

// For ac060014ec0f9700... it's (0x06 << 7) + (0xAC & 127) - 2 = 810 bytes

I could not understand 5 and 6, as well as the magic subtraction of -3 and -2.

I'm trying to figure out how to decode the packet length field in order to be able to process them. The server often sends multiple concatenated data packets in one response, and the only way to separate them is to decode their size.
Maybe there is some algorithm for such a length record? Maybe someone has encountered something like this and knows these encoding rules?

EDIT: I found this algorithm, it's LEB128.

Upvotes: 1

Views: 69

Answers (0)

Related Questions