The problem is that the i template needs at least 32 bits, but you're only giving it 8. The $size argument to bin2dec should be 32, but even then your function won't always work depending on the endianness of your system!

$ perl -wMstrict -le 'print unpack("B*",pack("i",3))' 00000011000000000000000000000000 $ perl -wMstrict -le 'print unpack("i",pack("B*", "00000011000000000000000000000000"))' 3 $ perl -wMstrict -le 'print unpack("i",pack("B*", "00000000000000000000000000000011"))' 50331648 $ perl -wMstrict -le 'print unpack("i",pack("B*","00000011")).""' Use of uninitialized value in concatenation (.) or string at -e line 1 +. $ perl -wMstrict -le 'print unpack("c",pack("B*","00000011"))' 3

(Note the use of "B*" instead of "B$size".) Some more general observations:

The i template is system-dependent. Unless the binary data itself is system-dependent, such as from C structs, I'd only use the system-independent formats, in this case for example the cCnNvV formats since those have a fixed size and endianness.

You say want to use i, but then only want handle 8 bits, that does not go together - why not use c to begin with? Also, you're not checking that your values will actually fit in 8 bits!

Lastly, I suspect you've got an XY Problem and you might want to explain to us what you're trying to accomplish overall. Don't worry about asking too many questions, but I would suggest you play around with pack and unpack a bit more, like I did above!


In reply to Re: pack and unpack with 8 bit integers by Anonymous Monk
in thread pack and unpack with 8 bit integers by thanos1983

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.