This bin2dec has a limitation of 32 bits, however, because it internally converts to an integer. What I need is bin2dec for binary strings of any length.
Using a full big number library like Math::Bigint for it is a bit of an overkill since I only need binary to decimal conversion. So, I've come up with the following trick:
The idea is that there are no long overflows in binary to decimal conversion. I'm shifting the binary number from left to right (msbits first), multiplying by 2 for each shift and adding 1 if the bit is 1. So, all I need is to implement multiplication by 2 (with a possible addition of 1) on string decimals, and that's quite simple (as demonstrated in mul2) because for these operations the carry can be maximum 1.print bin2dec("1110010101011101111011110110101010111"); # Calculate a (arbitrarily large) decimal number from its # binary representation # sub bin2dec { my ($str) = @_; my $ret = ""; $ret = mul2($ret, $_) foreach split(//, $str); return $ret; } # Given a (arbitrarily large) decimal number N as a string, # returns 2N or 2N+1 # sub mul2 { my ($str, $add_one_f) = @_; defined($add_one_f) or $add_one_f = 0; my $ret = ""; foreach (my $i = length($str) - 1; $i >= 0; --$i) { my $c = substr($str, $i, 1) * 2; $c += 1 if ($add_one_f); $ret = ($c % 10) . $ret; $add_one_f = ($c >= 10); } return $add_one_f ? '1' . $ret : $ret; }
I'll be glad if someone finds this code useful.
Naturally, ideas for improvements/optimization will be welcomed. My initial implementation was in C++ so this code is a direct translation, and as such can feel "C++ish". More Perlish techniques will be welcomed.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: bin2dec for big numbers
by Aristotle (Chancellor) on Jan 18, 2005 at 12:11 UTC | |
by spurperl (Priest) on Jan 18, 2005 at 13:03 UTC | |
by Aristotle (Chancellor) on Jan 18, 2005 at 13:13 UTC | |
|
Re: bin2dec for big numbers (use Math::BaseCalc)
by grinder (Bishop) on Jan 18, 2005 at 11:37 UTC | |
by spurperl (Priest) on Jan 18, 2005 at 12:07 UTC | |
by spurperl (Priest) on Jan 18, 2005 at 11:40 UTC | |
|
Re: bin2dec for big numbers
by hv (Prior) on Jan 18, 2005 at 14:24 UTC | |
|
Re: bin2dec for big numbers
by merlyn (Sage) on Jan 18, 2005 at 10:33 UTC | |
by Aristotle (Chancellor) on Jan 18, 2005 at 11:17 UTC | |
by spurperl (Priest) on Jan 18, 2005 at 11:43 UTC | |
|
Re: bin2dec for big numbers
by TilRMan (Friar) on Feb 26, 2005 at 18:40 UTC |