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;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|