Anonymonk:

Here's another way to do it:

$ cat bin2hex.pl #!/usr/bin/perl use strict; use warnings; for my $b (qw(101101110101001010010100101000101011101010101010101010 1 10 101 1010 10101 101010 11010011 000000000000001 000 +1111 11111 11000011 )) { print "$b --> ", bin2hex($b), "\n"; } sub bin2hex { my $bin = shift; # Make input bit string a multiple of 4 $bin = substr("0000",length($bin)%4) . $bin if length($bin)%4; my ($hex, $nybble) = (""); while (length($bin)) { ($nybble,$bin) = (substr($bin,0,4), substr($bin,4)); $nybble = eval "0b$nybble"; $hex .= substr("0123456789ABCDEF", $nybble, 1); } return $hex; } $ perl bin2hex.pl 101101110101001010010100101000101011101010101010101010 --> 2DD4A528AEA +AAA 1 --> 1 10 --> 2 101 --> 5 1010 --> A 10101 --> 15 101010 --> 2A 11010011 --> D3 000000000000001 --> 0001 0001111 --> 0F 11111 --> 1F 11000011 --> C3

It uses an old[1] trick: Since each "nybble"[2] represents a decimal value from 0 to 15, you can build a 16 character string of digits, and use the nybble value as the index of a character.

Then, to simplify things, we ensure that the string is a multiple of four characters long. That way, we simply chop off four characters, turn it into a hex digit, repeating until the string is consumed.

Notes:

[1] How old? It was old when I learned it, roughly 35 years ago.

[2] Four bits == half a byte, thus, a nybble.

...roboticus

When your only tool is a hammer, all problems look like your thumb.


In reply to Re^5: How to convert binary to hexadecimal by roboticus
in thread How to convert binary to hexadecimal by vaas_m

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.