Here's another way to do it.
use warnings;
use strict;
foreach (
qw(
00
1010
1110
010001
01101011
),
'1' x 33,
'0101' x 16
) {
my $h2 = b2h2($_);
$h2 =~ s/(\w{4})\B/$1 /g;
print "$_ $h2 width=", length($_), "\n\n";
}
sub b2h2 {
my $bin = shift;
my $extra_characters = length($bin)%16;
$bin = '0' x (16-$extra_characters) . $bin if $extra_characters;
$bin =~ s/([01]{4})/sprintf "%X", oct("0b$1")/eg;
return $bin;
}
__END__
Output:
00 0000 width=2
1010 000A width=4
1110 000E width=4
010001 0011 width=6
01101011 006B width=8
111111111111111111111111111111111 0001 FFFF FFFF width=33
0101010101010101010101010101010101010101010101010101010101010101 5555
+5555 5555 5555 width=64
Here is a way to convert without padding with zeros on the left side. Reverse the binary string and convert groups of four bits then reverse the final string.
sub b2h {
my $revbin = reverse shift;
$revbin =~ s/([01]{1,4})/sprintf "%X", oct('0b' . reverse $1)/eg;
return reverse $revbin;
}