in reply to Need help with (un)pack templates

C is a 8-bit byte. a2 is a two byte string; a* a variable length string.

Bytes and strings do not have "endianess". Only multi-byte numbers.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"I'd rather go naked than blow up my ass"

Replies are listed 'Best First'.
Re^2: Need help with (un)pack templates
by Subop (Acolyte) on Dec 20, 2009 at 13:58 UTC

    Hey BrowserUk!

    I've read the docs on (un)pack, so I understand what the characters in the template represent. I just don't understand when I'm supposed to use those characters. For example, in the above code for decoding an IP packet, which is network data-- How am I supposed to know I shouldn't be using "n" or "N" to decode the network data?

      How am I supposed to know I shouldn't be using "n" or "N" to decode the network data?

      That's a tough question to answer in full. Essentially, you have to know what format the data you are trying to decode is in.

      For example,

      • Fields 1 & 2 are both 4-bits, hence the template you have extracts them both as a single 8.bit number, which is presumably broken down further later in the code.
      • Field 3 is is an 8-bit number, and extracted as such.
      • Field 4 is a 16-bit number, hence they use 'n' to extract it.
      • Field 5 Ditto.
      • Fields 6 & 7 are 3 & 13 bits respectively. But as #7 crosses a byte boundary, they extract the two as a single 16-bit number (the third 'n'), and then (presumably) break that down furtehr later in the code.
      • etc. ...

      Without knowing what the format of the data you have is, there is no way to know what templates are applicable.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.