why we need to add a 'pack/unpack' behavior while transfering data?

When the data is sent over a stream (e.g. a TCP socket), the reader has no way of knowing where the data ends.

For example, if I told you "THE FOX IS BROWN", would you know if my sentence is done? If I continued with "AND FAST", is it part of this sentence, or is it the start of another?

One solution is to use a terminal (the period of a sentence, for example) to mark the end of the data. Another solution is to prepend the data with its length (as in your code snippet).

How do I convert decimal to hex,oct,bin or others? or I should use sprintf?

For starters, the number is not stored in base 10. 255, 0xFF, 250+5 are all stored identically, so calling your number a "decimal" is wrong unless you mean it's not an integer.

"Converting a number to hex/oct/bin" and "Formatting a number as hex/oct/bin" are short ways of saying "getting the string representation of a number in hex/oct/bin". sprintf is all about formatting numbers, so it's a very appropriate function to use. Other means can probably be used, but they won't be as readable.


In reply to Re: question of pack. by ikegami
in thread question of pack. by xiaoyafeng

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.