Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is there a function to convert from binary to hexadecimal?

Status
Not open for further replies.

SparceMatrix

Technical User
Mar 9, 2006
62
US
I've looked up all the permutations using "oct" and don't see a solution there. "hex" won't do it. If "sprintf" will do it, I can't tell from the documentation and "unpack" is even more obtuse. A staged conversion such as binary -> decimal -> hexadecimal won't do, it must be binary -> hexadecimal.

A simple question ... anyone?
 

You might use a hash containing all sixteen hex charactors (eg - $hash{1101}="B") and a regex to match the rightmost four charactors. Maybe something like:

$hex = "";
$_ = $bin;
$hex = $hash{/(0|1){4}$/} . $hex;
s/(0|1){4}$//;
(repeat as needed)

...not sure if precisely this will work, though. Haven't messed with hashes much. Anybody else want to flesh this out?
 
This'll work:

my %hex = (
0000 => '0',
0001 => '1',
0010 => '2',
0011 => '3',
0100 => '4',
0101 => '5',
0110 => '6',
0111 => '7',
1000 => '8',
1001 => '9',
1010 => 'A',
1011 => 'B',
1100 => 'C',
1101 => 'D',
1110 => 'E',
1111 => 'F',
);


my $x = '110111011111101111101000110000';


my $hexnumber = '';

while($x=~/(....)/g){

$hexnumber .= $hex{$1};

}

print $hexnumber . "\n";


 
Thanks all, but I bumped into a nice module over at ActiveState,


I copy and pasted the example and with a few alterations, got exactly what I was looking for:

Code:
#!/usr/bin/perl

use Math::BaseCalc;

$calc1  = new Math::BaseCalc(digits=>[0,1]);
$calc63 = new Math::BaseCalc(digits=>[0..9,'a'..'z','A'..'Z']);

$MyHugeBinary =  "1" x 192;

$in_base_63 = $calc63->to_base( $calc1->from_base($MyHugeBinary) );

print $in_base_63;
print "   And the length is ... ". length( $in_base_63 ). "\n";
print "... as opposed to ". length($MyHugeBinary). "\n";
 

One thing I noticed is that your hex has to be a multiple of four, or you lose some digits. Maybe some leading zeros should be tacked on? How about changing the regex to

while($x=~/(.{1-4})/g){

...then the hex doesn't need to be a multiple.

Another problem is if regex's process from left to right, in which case, if the hex isn't a multiple of four, the clustering would be out of phase, and the result would be wrong.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top