Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??
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.


In reply to Re^3: How to convert binary to hexadecimal by toolic
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!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others meditating upon the Monastery: (5)
    As of 2014-07-13 10:46 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      When choosing user names for websites, I prefer to use:








      Results (249 votes), past polls