Hello brethen,
I am working on decoding a network packet using perl-- however, unpack puzzles me and I fear I have a lack of understanding about this function.
First of all-- why does this
printf("%d\n", unpack ("h", "F")); produce '6' on my system? Is it because the string "F" is treated as a blob of binary data and therefore this does not really make sense? If so, then should not
printf("%d\n", unpack ("h", pack ("h", "F")); produce 16?
This puzzles me.
Question 2. I have (seemingly successfully) done this:
my ($v1, $rest) = unpack ("C4 a*", $packet);
my ($l, $payload) = unpack ("C2 a*, $rest);
If i
printf("%d\n", $l) i get 0.
However, exchanging the last line with
my ($l, $payload) = unpack ("H4 a*, $rest);
and print it, I get a 1, which seems correct from a protocol-perspective.
This puzzles me further.
How are these in-data strings actually converted? Am I correct in assuming that unpack simply formats data, regardless of input?
The final question is: Is it OK to use
my ($value) = unpack ("C4", $packet); and then treat $value as any number, i.e.
$field = ($value & 0x80000000) >> 24;?
If I instead do
my ($value) = unpack ("H8", $packet);, what am I in reality doing?
Solution and enlightenment
A colleague of mine figured it out, and I am humbled. Here is the cinch: H6 represents a
string -- and it is perfectly fine to want a string of 3 bytes like that. However, C3 is
not a string, it is 3 octets following each other, and to unpack it I shall have to use a list of 3 elements.
Today I have learned many things.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.