that doesn't sound right ...
If you have the value 2 which has to be put into a long register as 00 00 00 02 how is Perl supposed to guess that 4 bytes are needed and 02 isn't already sufficient?
But if your transfer protocol was able to handle 02 for a long register, why would anyone need to stuff any leading/trailing 0s into it?
The straight mathematical way to tell the "width" of a number is using log like already shown. But given your demonstrated code I'd rather suggest you sticking with 3 if-then-else levels inside a sub.
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery