Since the code Does What I Want (works even for bit widths > 32), I have made it readable by using perltidy. I have also made it strict and removed the print statements:
use warnings FATAL => 'all';
use strict;
for (
qw(
00
1010
1110
010001
01101011
),
'1' x 33,
'0101' x 16
) {
my $h = b2h($_);
print "$_ $h width=", length($_), "\n";
}
exit;
sub b2h {
my $num = shift;
my $WIDTH = 32;
my $index = length($num) - $WIDTH;
my $hex = '';
do {
my $width = $WIDTH;
if ($index < 0) {
$width += $index;
$index = 0;
}
my $cut_string = substr($num, $index, $width);
$hex = sprintf('%X', oct("0b$cut_string")) . $hex;
$index -= $WIDTH;
} while ($index > (-1 * $WIDTH));
return $hex;
}
__END__
Output:
00 0 width=2
1010 A width=4
1110 E width=4
010001 11 width=6
01101011 6B width=8
111111111111111111111111111111111 1FFFFFFFF width=33
0101010101010101010101010101010101010101010101010101010101010101 55555
+55555555555 width=64
I have also been attempting to implement this with pack and unpack, to no avail. |