Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^4: How to convert binary to hexadecimal

by Lotus1 (Vicar)
on Oct 02, 2014 at 17:46 UTC ( [id://1102655]=note: print w/replies, xml ) Need Help??


in reply to Re^3: How to convert binary to hexadecimal
in thread How to convert binary to hexadecimal

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; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1102655]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (6)
As of 2024-04-19 06:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found