Thanks for the further information, I look forward to seeing your code.

Unsigned integers of almost any size aren't a problem. You can mask a value before handing it off to pack, e.g. pack("C", 5 & 0b111) will get you the value 5 represented as the lowest 3 bits of the returned byte (the masking is not even necessary if you know your input is in the proper range). The inverse would be to unpack and then mask the value.

It gets a little more complicated if you want signed integers, as you have to perform Sign extension as previously mentioned.

In general, it is important to remember to check the range of the value you want to store, so that there are no unexpected overflows!

Since I am not really experienced with binaries I tried to do my best, and I hope that the scripts will have minimum possible bugs.

When in doubt, test, test, test! Your two conversion functions to and from 3-bit numbers only require 8 test cases each (plus maybe a few to check for invalid values), that's no problem to write up, and you'll have immediate certainty that your conversion functions work. Even if it sometimes gets a little annoying to write lots of test cases, they are your safety net. And with some practice it gets easier and easier to properly modularize your code so that it's more easily tested.


In reply to Re^5: 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.