in reply to Re^4: pack and unpack with 8 bit integers
in thread pack and unpack with 8 bit integers

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.

Replies are listed 'Best First'.
Re^6: pack and unpack with 8 bit integers
by thanos1983 (Parson) on Sep 23, 2014 at 14:51 UTC

    Hello Anonymous Monk,

    Again thank you for your time and effort reading and replying on my question. I was not aware that I could mask the value. Hmmm maybe I should take a look on it, I have never tried something similar to that. Well there is always first time for everything.

    Finally I manage to finalize the code and I have released it for comments from experts just like you. Here is a link to the post SNTP Client/Server V2 RFC. This is only a best version, because I guess I will have many errors that I need to take care of.

    When in doubt, test, test, test!

    If you see how many small scripts I have created just for the conversion of decimals, floating points to binary and vice versa you will laugh with me. But as you said it was the only way.

    Thank you again for your time and effort.

    Seeking for Perl wisdom...on the process of learning...not there...yet!