Binary to Decimal – Doubling

I really didn’t know that there is an easier way of converting from binary to decimal as shown in the wikihow article. The main advantage of this method is we don’t have to compute the powers of 2 (as shown in the positional notation method of the given article). Another advantage is that this method is generic and can be used for any base to decimal conversion.

Let us jump to the code now.

use strict;
use warnings;

sub bin2dec_doubling {
    my ($bin, $sum) = @_;
    $sum = 0     if not defined $sum;
    return $sum  if $bin eq '';
    bin2dec_doubling((substr $bin, 1), 2 * $sum + (substr $bin, 0, 1));
}

print bin2dec_doubling($ARGV[0]), "\n";

The code doesn’t deal with positional notation method but only with the doubling method. Also, it is pretty much easy to write the logic using procedural language like Perl (hardly 4 lines). What about SQL?

with recursive
binnum as (select '1011001'::text as str),

tmp as (
select ''::text as curdigit, cast(0 as numeric) as sum, 0 as level
 union all
select substr(binnum.str, level + 1, 1), sum(2 * sum + cast(substr(binnum.str, level + 1, 1) as int)) over (), level + 1
  from tmp cross join binnum
 where substr(binnum.str, level + 1, 1) <> ''
)

select max(sum) from tmp;

The above SQL snippet is tested on PostgreSQL 9.4 and yes it is not pretty formatted.
Hope you get some idea from this.

Happy Programming!