[Israel.pm] printf and hex2bin

Offer Kaye offer.kaye at gmail.com
Thu Oct 21 06:13:36 PDT 2004


Hi,
I'm using printf to convert a hexadecimal number to binary and print
it, and I need some help from any printf expert out there:

#################################
hex2bin('4b');

sub hex2bin {
   my $hex = shift;
   printf "$hex (base 16) = 0b%0*b (base 2)\n",4*length $hex, hex $hex;
}
#################################

Questions:
1. I'd like to use a "#" sign in the format spec to print the "0b",
instead of using a literal "0b". However, it looks like if I'm using
"0*" I can't also use "#". Is this correct?

2. I'd like to add an "_" char between each group of 4 binary digits. 
Is there some way to do this using the printf functionality itself, or
do I have to use sprintf and "massage" the result using a s/// or
split/join?

Thanks in advance,
-- 
Offer Kaye



More information about the Perl mailing list