|
|
| Think about Loose Coupling | |
| PerlMonks |
bin2dec for big numbersby spurperl (Priest) |
| on Jan 18, 2005 at 08:43 UTC ( #422936=CUFP: print w/replies, xml ) | Need Help?? |
|
I'm employing Perl for a lot of data crunching, converting between various data formats, etc. There's a nice snippet in the Cookbook named bin2dec - to convert binary numbers (given as strings) to decimals. Like "10011" to "19". 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. 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.
Back to
Cool Uses for Perl
|
|
||||||||||||||||||||||||||||||||||||||||||||||||