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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.