[Israel.pm] printf and hex2bin

Mikhael Goikhman migo at homemail.com
Thu Oct 21 06:49:05 PDT 2004


On 21 Oct 2004 15:13:36 +0200, Offer Kaye wrote:
> 
> 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?

Not quite. "%#0*b" works like expected for me. But you should adjust
the length if you want to use it, i.e. 4 * length $hex + 2.

> 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?

I would use sprintf in the first place. I don't like functions with
unconditional side effects unless these effects are noted in their
name, i.e. print_hex2bin.

I don't think that sprintf may add "_" automatically for you. When I need
something like this, I use this one-liner loop:

  $number = "0b100111000011111";
  while ($number =~ s/(\d)(\d{4})(_|$)/${1}_$2$3/) {}
  print $number, "\n";

Regards,
Mikhael.

-- 
perl -e 'print+chr(64+hex)for+split//,d9b815c07f9b8d1e'



More information about the Perl mailing list