bytes_to_short(short_to_bytes($x)) is not equal to $x on all platforms. Use v instead. (Using "L" to convert shorts is silly anyway.)

Furthermore, "short" is a very ambiguous term. It doesn't necessarily mean 16 bits, and it definitely doesn't imply unsigned (as your code expects).

sub uint16_to_bytes { my ($int) = @_; return unpack('C2', pack('v', $int)); } sub bytes_to_uint16 { my ($lo, $hi) = @_; return unpack('v', pack('C2', $lo, $hi)); } sub int16_to_bytes { my ($int) = @_; return unpack('C2', pack('v', unpack('S', pack('s', $int)))); } sub bytes_to_int16 { my ($lo, $hi) = @_; return unpack('s', pack('S', unpack('v', pack('C2', $lo, $hi)))); }

In reply to Re: Int ->Bytes -> Int by ikegami
in thread Int ->Bytes -> Int by JosiahBryan

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.